当前位置:   article > 正文

WPF中Converter的使用_wpf 变量变化时自动convert

wpf 变量变化时自动convert

WPF中Converter的用于对数据的转换。以下实例将实现将数据中的性别属性的转换(0:男,1:女)。

1、创建SexConverter.cs类,并实现IValueConverter接口

  1. public class SexConverter : IValueConverter
  2. {
  3. public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  4. {
  5. string result = "";
  6. string sex = (string)value;
  7. if (sex == "0")
  8. {
  9. result = "男";
  10. }
  11. else if (sex == "1")
  12. {
  13. result = "女";
  14. }
  15. return result;
  16. }
  17. public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  18. {
  19. throw new NotImplementedException();
  20. }
  21. }

2、在XAML页面中使用

  1. <Window.Resources>
  2. <!--引用资源-->
  3. <converter:SexConverter x:Key="SexConverter"/>
  4. <Style TargetType="ListBoxItem">
  5. <Setter Property="ContentTemplate">
  6. <Setter.Value>
  7. <DataTemplate>
  8. <StackPanel Orientation="Horizontal">
  9. <TextBlock Text="{Binding ID}" Width="60"/>
  10. <TextBlock Text="{Binding Name}" Width="120"/>
  11. <TextBlock Text="{Binding Sex,Converter={StaticResource SexConverter}}" Width="60"/>
  12. </StackPanel>
  13. </DataTemplate>
  14. </Setter.Value>
  15. </Setter>
  16. </Style>
  17. </Window.Resources>
  18. <StackPanel>
  19. <ListBox x:Name="listBoxStudent" Margin="5"/>
  20. </StackPanel>

后台代码

  1. /// <summary>
  2. /// MainWindow.xaml 的交互逻辑
  3. /// </summary>
  4. public partial class MainWindow : Window
  5. {
  6. public MainWindow()
  7. {
  8. InitializeComponent();
  9. List<Student> stuList = new List<Student>(){
  10. new Student(){ID="1",Name="Peter",Sex="0"},
  11. new Student(){ID="2",Name="Tom",Sex="1"},
  12. new Student(){ID="3",Name="Ben",Sex="0"}
  13. };
  14. this.listBoxStudent.ItemsSource = stuList;
  15. }
  16. }
  17. /// <summary>
  18. /// 学生类
  19. /// </summary>
  20. public class Student{
  21. public string ID{get;set;}
  22. public string Name { get; set; }
  23. public string Sex { get; set; }
  24. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/537649
推荐阅读
相关标签
  

闽ICP备14008679号