C# wpf 实现Converter定义与使用

发布时间 2023-07-10 17:26:44作者: WebEnh

1.  本身的值0, 如何转换为“男” 或“女”呢,可以定义sexConverter继承自IValueConverter
即可,代码如下:

[ValueConversion(typeof(int), typeof(string))]
    public class sexConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string result = "";
            string sex = (string)value;
            if (sex == "0")
            {
                result = "男";
            } else if (sex == "1") {
                result = "女";
            }
            return result;
        }
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

 

2. 页面使用

<Window.Resources>
        <local:ForeColorConverter x:Key="foreColor"></local:ForeColorConverter>
        <!--引用资源-->
        <local:sexConverter x:Key="sexConverter"/>
        <Style TargetType="ListBoxItem">
            <Setter Property="ContentTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="{Binding ID}" Width="50"/>
                            <TextBlock Text="{Binding Name}" Width="110"/>
                            <TextBlock Text="{Binding sex,Converter={StaticResource sexConverter}}" Width="60"/>
                        </StackPanel>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
    <Grid>
        <StackPanel>
            <ListBox x:Name="listBoxStudent" Margin="5"/>
        </StackPanel>
    </Grid>

3. cs 代码如下:
private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            stuList_ = new List<StudentInfo>(){
            new StudentInfo(){ID="1",Name="andy",sex="1"},
            new StudentInfo(){ID="2",Name="Tom1",sex="0"},
            new StudentInfo(){ID="3",Name="stdeven",sex="1"}
        };

            listBoxStudent.ItemsSource = stuList_;
        }
public class StudentInfo
    {
        public string ID { get; set; }
        public string Name { get; set; }
        public string sex { get; set; }
    }

4.效果如下: