IValueConverter
1.创建一个类集成接口IValueConverter,并实现
2在xaml中引入
举例
性别用int来表示,1为男,2为女
核心代码
创建GenderConverter继承IValueConverter
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中定义属性
public int Gender { get; set; }
xaml中引入
xmlns:convert="clr-namespace:TestConvert.Converter"
<Window.Resources><convert:GenderConverter x:Key="genderConverter" />
</Window.Resources>
xaml中IsChecked绑定Gender
<StackPanel Grid.Row="1" Orientation="Horizontal"><TextBlock Margin="10,0" Text="性别:" /><RadioButton Margin="0,0,10,0" Content="男" IsChecked="{Binding Gender, Converter={StaticResource genderConverter}, ConverterParameter=1}" /><RadioButton Content="女" IsChecked="{Binding Gender, Converter={StaticResource genderConverter}, ConverterParameter=2}" />
</StackPanel>
IMultiValueConverter
1.创建一个类集成接口IMultiValueConverter,并实现
2在xaml中引入
举例
只有当下拉框一个为A一个为B才会显示绿色,其他都为红色
核心代码
通过多帮获取两个对象的数据,在ComboBoxConverter中进行验证
public class ComboBoxConverter : IMultiValueConverter
{public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture){if (values[0].ToString() == "A"&& values[1].ToString() == "B"){return Brushes.Green;}else{return Brushes.Red;}}public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture){throw new NotImplementedException();}
}
xaml中引入Converter资源
xmlns:convert="clr-namespace:TestConvert.Converter"
<Window.Resources><convert:ComboBoxConverter x:Key="comboBoxConverter"
</Window.Resources>
xaml中引入ComboBoxConverter
<StackPanel Grid.Row="2" Orientation="Horizontal"><ComboBoxName="cb_001"Width="60"Height="25"Margin="0,30,0,0"HorizontalAlignment="Center"VerticalAlignment="Center"><ComboBoxItem Content="A" /><ComboBoxItem Content="B" /><ComboBoxItem Content="C" /></ComboBox><ComboBoxName="cb_002"Width="60"Height="25"Margin="0,10,0,0"HorizontalAlignment="Center"VerticalAlignment="Center"><ComboBoxItem Content="A" /><ComboBoxItem Content="B" /><ComboBoxItem Content="C" /></ComboBox><TextBlock Margin="0,20,0,0" HorizontalAlignment="Center" Text="Hello World!"><TextBlock.Foreground><MultiBinding Converter="{StaticResource comboBoxConverter}"><Binding Path="Text" ElementName="cb_001" /><Binding Path="Text" ElementName="cb_002" /></MultiBinding></TextBlock.Foreground></TextBlock>
</StackPanel>