怪奇物语

怪奇物语

首页 新随笔 联系 管理

converter wpf 转换器

流程图

graph LR classDef startend fill:#F5EBFF,stroke:#BE8FED,stroke-width:2px classDef process fill:#E5F6FF,stroke:#73A6FF,stroke-width:2px classDef decision fill:#FFF6CC,stroke:#FFBC52,stroke-width:2px A([开始]):::startend --> B(数据绑定触发转换):::process B --> C{数据流向}:::decision C -->|Model -> View| D(调用 Convert 方法):::process C -->|View -> Model| E(调用 ConvertBack 方法):::process D --> F{value 是否为 bool 类型, 然后转换成boolValue}:::decision F -->|是| G(获取 parameter 作为 trueText 或默认 'True'):::process F -->|否| H(直接返回 value):::process G --> I{culture 是否为中文区域}:::decision I -->|是| J(设置 trueText 为 '是',falseText 为 '否'):::process I -->|否| K(设置 falseText 为 'False'):::process J --> L{boolValue 是否为 true}:::decision K --> L L -->|是| M(返回 trueText):::process L -->|否| N(返回 falseText):::process M --> O(更新 TextBlock 的 Text 属性):::process N --> O E --> P{value 是否为 string 类型,然后转换成textValue}:::decision P -->|是| Q(获取 parameter 作为 trueText 或默认 'True'):::process P -->|否| R(直接返回 value):::process Q --> S{culture 是否为中文区域}:::decision S -->|是| T(设置 trueText 为 '是',falseText 为 '否'):::process S -->|否| U(设置 falseText 为 'False'):::process T --> V{textValue 是否等于 trueText}:::decision U --> V V -->|是| W(返回 true):::process V -->|否| X(返回 false):::process W --> Y(更新 MainWindowModel 的 IsChecked 属性):::process X --> Y H --> Z([结束]):::startend O --> Z R --> Z Y --> Z

WpfApp1\BoolToTextConverter.cs


using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;

namespace WpfApp1.Converter
{

    public class BoolToTextConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            // 检查 value 是否为 bool 类型
            if (value is bool boolValue)
            {
                // 根据参数和区域性信息进行转换
                string trueText = parameter?.ToString() ?? "Yes";
                string falseText = "No";

                // 根据 culture 调整文本显示
                if (culture.Name.StartsWith("zh"))
                {
                    trueText = "是";
                    falseText = "否";
                }

                return boolValue ? trueText : falseText;
            }

            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            // 检查 value 是否为 string 类型
            if (value is string textValue)
            {
                string trueText = parameter?.ToString() ?? "Yes";
                string falseText = "No";

                // 根据 culture 调整文本判断
                if (culture.Name.StartsWith("zh"))
                {
                    trueText = "是";
                    falseText = "否";
                }

                return textValue.Equals(trueText, StringComparison.OrdinalIgnoreCase);
            }

            return value;
        }
    }
}

WpfApp1\MainViewModel.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfApp1
{
    public class MainWindowModel
    {
        public bool IsChecked { get; set; }

        public MainWindowModel()
        {
            IsChecked = false;
        }
    }
}

WpfApp1\MainWindow.xaml


<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇
        xmlns:converter="clr-namespace:WpfApp1.Converter"
        mc:Ignorable="d"
        Title="MainWindow" Height="200" Width="200">

    <Window.Resources>
        👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇
        <converter:BoolToTextConverter x:Key="Bool2TextCov"/>
    </Window.Resources>

    <Grid HorizontalAlignment="Center" VerticalAlignment="Center">
        <StackPanel>

                                               👇👇👇👇👇👇👇👇👇👇👇👇👇
            <CheckBox Content="选择" IsChecked="{Binding IsChecked, Mode=TwoWay}"/>
                            👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇
            <TextBlock Text="{Binding IsChecked, Converter={StaticResource Bool2TextCov}, Mode=OneWay}"/>
        </StackPanel>
    </Grid>
</Window>


WpfApp1\MainWindow.xaml.cs


using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MainWindowModel();
        }
    }
}

WpfApp1\WpfApp1.csproj


<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net8.0-windows</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <UseWPF>true</UseWPF>
  </PropertyGroup>

</Project>

WpfApp1\WpfApp1.sln


Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.2.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WpfApp1", "WpfApp1.csproj", "{C5E909BA-3C30-04C8-EE6C-B85DCBBE0461}"
EndProject
Global
	GlobalSection(SolutionConfigurationPlatforms) = preSolution
		Debug|Any CPU = Debug|Any CPU
		Release|Any CPU = Release|Any CPU
	EndGlobalSection
	GlobalSection(ProjectConfigurationPlatforms) = postSolution
		{C5E909BA-3C30-04C8-EE6C-B85DCBBE0461}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
		{C5E909BA-3C30-04C8-EE6C-B85DCBBE0461}.Debug|Any CPU.Build.0 = Debug|Any CPU
		{C5E909BA-3C30-04C8-EE6C-B85DCBBE0461}.Release|Any CPU.ActiveCfg = Release|Any CPU
		{C5E909BA-3C30-04C8-EE6C-B85DCBBE0461}.Release|Any CPU.Build.0 = Release|Any CPU
	EndGlobalSection
	GlobalSection(SolutionProperties) = preSolution
		HideSolutionNode = FALSE
	EndGlobalSection
	GlobalSection(ExtensibilityGlobals) = postSolution
		SolutionGuid = {13E17630-1AE5-43F5-9B61-7309D08D8AD7}
	EndGlobalSection
EndGlobal

posted on 2025-03-04 08:00  超级无敌美少男战士  阅读(93)  评论(0)    收藏  举报