效果 文本绑定颜色
首先实现一个颜色转换器类 继承IValueConvert接口
class ColorValueConvert : IValueConverter { #region Field 字段 #endregion #region Constructor 构造函数 #endregion #region Property 属性 #endregion #region Event 事件 #endregion #region Method 方法 #endregion /// /// 颜色转换器 /// /// /// /// /// /// public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var colorString = value.ToString().Split(new char[] { ':' })[1].Trim();//颜色文本; var flag = System.Convert.ToBoolean(parameter);//确是否转换 if (flag) { switch (colorString) { case "红色": return Brushes.Red; case "绿色": return Brushes.Green; case "蓝色": return Brushes.Blue; case "紫色": return Brushes.Violet; default: return Brushes.Transparent; } } return null; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } }
在界面中引用转换器
xmlns:convert="clr-namespace:值转换器"
创建资源
使用
<StackPanel VerticalAlignment="Center" Orientation="Vertical"><ComboBox x:Name="cbox" Width="300" SelectedIndex="0" Margin="10"><ComboBoxItem Content="红色" /><ComboBoxItem Content="绿色" /><ComboBoxItem Content="蓝色" /><ComboBoxItem Content="紫色" /><Rectangle Width="200" Height="200" Fill="{Binding ElementName=cbox, Path=SelectedItem, Converter={StaticResource colorConvert}, ConverterParameter=True}" />
界面完整代码
<Window x:Class="值转换器.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:convert="clr-namespace:值转换器" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:值转换器" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" Title="MainWindow" Width="800" Height="450" mc:Ignorable="d"><convert:ColorValueConvert x:Key="colorConvert" /><StackPanel VerticalAlignment="Center" Orientation="Vertical"><ComboBox x:Name="cbox" Width="300" SelectedIndex="0" Margin="10"><ComboBoxItem Content="红色" /><ComboBoxItem Content="绿色" /><ComboBoxItem Content="蓝色" /><ComboBoxItem Content="紫色" /><Rectangle Width="200" Height="200" Fill="{Binding ElementName=cbox, Path=SelectedItem, Converter={StaticResource colorConvert}, ConverterParameter=True}" />