WPF 值转换器(Converter)的使用 | 您所在的位置:网站首页 › 黄莺代表什么生肖 › WPF 值转换器(Converter)的使用 |
WPF 值转换器(Converter)的使用
示例一、ViewModel层int型属性Gender绑定界面表示性别的两个RadioButton,Gender=1表示男,Gender=2表示女; 后台代码: public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this.DataContext = new MainWindowModel(); } }MainWindowModel代码: namespace WpfApp1 { class MainWindowModel { public int Gender { get; set; } public MainWindowModel() { Gender = 2; } } }转换器代码: namespace WpfApp1.Converter { 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(); //throw new NotImplementedException(); } //view->model转换 public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { //throw new NotImplementedException(); return parameter; } } }示例二、如果ViewModel层的Flag属性的值为true时,窗体中的字体为绿色,否则字体为红色 后台代码: public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this.DataContext = new MainWindowModel(); } }MainWindowModel代码: namespace WpfApp1 { class MainWindowModel { public bool Flag { get; set; } public MainWindowModel() { Flag = false; } } }转换器代码: namespace WpfApp1.Converter { class BoolToBrushConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { //throw new NotImplementedException(); if (value != null && bool.Parse(value.ToString())) { return Brushes.Green; } return Brushes.Red; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }示例三、多值转换器 下图:只有当第一个ComboBox值为A,第二个ComboBox值为B时,下面的文本字体才为红色,否则均为灰色。 MainWindow.xaml代码: 示例四:多值转换器的使用二 下图:如果质量和服务评分都在60以上,则评价为✔;否则评价为✘; 主页面代码: 后台代码: public partial class MainWindow : Window { public MainWindow() { products = new List(); InitializeComponent(); products.Add(new { Name = "产品一", Score = 90, Service = 40}); products.Add(new { Name = "产品二", Score = 70, Service = 70 }); products.Add(new { Name = "产品三", Score = 50, Service = 80 }); DataContext = this; } public List products { get; set; } } |
CopyRight 2018-2019 实验室设备网 版权所有 |