Value Converter
首先需要添加引用
using System.Windows.Data;
internal class bool2InverterConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return !(bool)value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
UI设计绑定转换类
<Button Margin=“3” Content=“Start” x:Name=“btnStart”
IsEnabled=“{Binding LicenseExpired, Converter={StaticResource bool2Inverter}}”/>
UI 后台代码:
public partial class MainWindow : Window
{
public bool LicenseExpired { get; set; } = true;
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
}
设计一个布尔属性,初始化绑定到自身后,使用窗口类的布尔属性,初始值true,但是经过转换Converter={StaticResource bool2Inverter} 后,取反
值 True取反,所以Button是Disable
internal class bool2IntConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (bool)value ? 5:2;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return System.Convert.ToInt32(value) < 5 ? false : true;
}
}
如果是true 返回整数5,否则返回2
UI设计绑定
添加Windows 资源:
<local:bool2IntConverter x:Key=“bool2Int”/>
绑定Window资源转换类
<Border Grid.Row=“1” Margin=“3” x:Name=“bd”
BorderThickness=“{Binding HasThickBorder,Converter={StaticResource bool2Int }}” BorderBrush=“Black”>
<TextBlock Text=“{Binding ElementName=bd,Path=BorderThickness,UpdateSourceTrigger=PropertyChanged}”
FontSize=“{Binding BoolProperty ,Converter={StaticResource bool2Int},Mode=OneWayToSource}”/>
HasThickBorder 窗口类的属性字段
public bool HasThickBorder { get; set; } = true;
public bool BoolProperty { get; set; }=true;
internal class Int2StringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (parameter != null)
return System.Convert.ToInt32(parameter) >= 60?“Passed”:“Failed”;
else
return System.Convert.ToInt32(value)>=60 ?“Passed”:“Failed”;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return System.Convert.ToInt32(value) < 15 ? false : true;
}
}
UI设计
<local:Int2StringConverter x:Key=“Int2Str”/>
UI后台代码设计字段:
public int Grade { get; set; } = 50;
转换类型
internal class StringEmpty2BoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value.ToString().Equals(string.Empty)?false:true;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return System.Convert.ToInt32(value) < 15 ? false : true;
}
}
<local:StringEmpty2BoolConverter x:Key=“str2Bool”/>
输入字符串为空时,Button 不可用,字符串输入不为空时,Enable