怪奇物语

怪奇物语

首页 新随笔 联系 管理

WPF 值转换器 Converter

流程图

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{值和参数是否为空}:::decision F -->|是| G(返回 false):::process F -->|否| H{值和参数是否相等}:::decision H -->|是| I(返回 true):::process H -->|否| J(返回 false):::process E --> K(返回参数值):::process G --> L(更新 RadioButton 的 IsChecked 属性):::process I --> L J --> L K --> M(更新 MainWindowModel 的 Gender 属性):::process L --> N([结束]):::startend M --> N

窗体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="250" Width="400">
    <Window.Resources>
        <converter:GenderConverter x:Key="genderConverter"/>
    </Window.Resources>
    <Grid HorizontalAlignment="Center" VerticalAlignment="Center">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="性别:" Margin="10 0"/>
            <RadioButton Content="男" IsChecked="{Binding Gender,Converter={StaticResource genderConverter},ConverterParameter=1}" Margin="0 0 10 0"/>
            <RadioButton Content="女" IsChecked="{Binding Gender,Converter={StaticResource genderConverter},ConverterParameter=2}"/>
        </StackPanel>
    </Grid>
</Window>

后台代码:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        this.DataContext = new MainWindowModel();
    }
}

MainWindowModel 代码:

public class MainWindowModel
{
    public int Gender { get; set; }

    public MainWindowModel()
    {
        Gender = 2;
    }
}

转换器代码

public class GenderConverter : IValueConverter
{
    //model->view
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null || parameter == null)
            return false;
        return value.ToString() == parameter.ToString();
    }

    //view->model
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        //throw new NotImplementedException();
        return parameter;
    }
}
posted on 2025-03-04 08:00  超级无敌美少男战士  阅读(33)  评论(0)    收藏  举报