我的目标是根据数据源的某个文本属性更改控件的背景(刷)。
我在一个简单(工作的)示例中实现了这一点,当我的转换器只有两个属性用于刷时:
<local:ListErrorWarndescriptionToColorConverter x:Key="ErrorListToColor"
NormalBrush="Transparent" ErrorBrush="Red" WarnBrush="Yellow"/>下一步是编写转换程序来处理两个以上的字符串。
我的转换器代码:
public class StringToBrushDictionary : Dictionary<string, Brush> { }
[ValueConversion(typeof(string), typeof(Brush))]
public sealed class TextToBrushConverter : IValueConverter
{
public StringToBrushDictionary LookUpTable { get; set; }
public Brush Default { get; set; }
public TextToBrushConverter()
{
// set defaults
LookUpTable = new StringToBrushDictionary();
Default = Brushes.Transparent;
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var collection = value as string;
if (collection == null)
return Default;
if (LookUpTable.ContainsKey(collection))
return LookUpTable[collection];
return Default;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}我现在的问题是:如何在xaml中填充字典--我找到了this 8 year old question --但这并不是我所需要的,因为它使用了字符串和int,这是两种“原生”数据类型,也使用VS 2010,后者不支持字典(根据那里的答案)。那里的一个答案是,后来的XAML版本可以做到这一点,但是VS 2010还没有实现它。
下面是我对转换器标记的看法,以及我已经尝试过的内容:
<Application x:Class="BetterListbox.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:BetterListbox"
xmlns:System="clr-namespace:System;assembly=mscorlib"
xmlns:collections="clr-namespace:System.Collections;assembly=mscorlib"
xmlns:Specialized="clr-namespace:System.Collections.Specialized;assembly=System"
StartupUri="MainWindow.xaml">
<Application.Resources>
<BooleanToVisibilityConverter x:Key="BoolToVis" />
<local:ListErrorWarndescriptionToColorConverter x:Key="ErrorListToColor"
NormalBrush="Transparent" ErrorBrush="Red" WarnBrush="Yellow"/>
<local:TextToBrushConverter x:Key="WarnErrorToBrush" Default="Red">
<local:TextToBrushConverter.LookUpTable>
<local:StringToBrushDictionary>
<Brush x:Key="Error" >
...?
</Brush>
<collections:DictionaryEntry x:Key="d" Value="Brushes.Red" />
</local:StringToBrushDictionary>
</local:TextToBrushConverter.LookUpTable>
</local:TextToBrushConverter>
</Application.Resources>
</Application>是否有可能在xaml中填写LookUpTable,如果有,如何填写?
发布于 2018-02-15 08:56:39
你可以这样填:
<my:TextToBrushConverter x:Key="textToBrush">
<my:TextToBrushConverter.LookUpTable>
<!-- LookUpTable["red"] = Brushes.Red -->
<x:Static MemberType="Brushes" Member="Red" x:Key="red" />
<!-- LookUpTable["aqua"] = new SolidColorBrush(Colors.Aqua) -->
<SolidColorBrush Color="Aqua" x:Key="aqua" />
<!-- custom color brush -->
<SolidColorBrush Color="#234433" x:Key="green" />
</my:TextToBrushConverter.LookUpTable>
</my:TextToBrushConverter>https://stackoverflow.com/questions/48803035
复制相似问题