我正在尝试将枚举转换为画笔,以便可以使用枚举变量来控制某些控件的颜色
我的枚举(不是很相关):
public enum Colors {
Red, Blue,
}
这是我的转换器:
[ValueConversion(typeof(Colors), typeof(Brush))]
public class EnumToBrushConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
return (Brushes.Red);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
throw new NotImplementedException();
}
}
在这里,我尝试使用它来根据枚举的值更改标签的颜色(Color 是 Colors 类型的公共属性):
<Grid>
<Grid.Resources>
<conv:EnumToBrushConverter x:Key="EnumToBrushConverter" />
</Grid.Resources>
<Label Content="fixed" Foreground="{Binding Path=Color, Converter=EnumToBrushConverter}" />
</Grid>
构建窗口时,出现以下异常:
System.Windows.Markup.XamlParseException occurred
Message='Set property 'System.Windows.Data.Binding.Converter' threw an exception.' Line number '9' and line position '11'.
Source=PresentationFramework
LineNumber=9
LinePosition=11
StackTrace:
at System.Windows.Markup.XamlReader.RewrapException(Exception e, IXamlLineInfo lineInfo, Uri baseUri)
at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
at TestCollectionChangingListbox.MainWindow.InitializeComponent() in c:\Users\stevez\Documents\Visual Studio 2010\Projects\TestCollectionChangingListbox\TestCollectionChangingListbox\MainWindow.xaml:line 1
at TestCollectionChangingListbox.MainWindow..ctor() in C:\Users\stevez\Documents\Visual Studio 2010\Projects\TestCollectionChangingListbox\TestCollectionChangingListbox\MainWindow.xaml.cs:line 29
InnerException: System.InvalidCastException
Message=Unable to cast object of type 'System.String' to type 'System.Windows.Data.IValueConverter'.
Source=PresentationFramework
StackTrace:
at System.Windows.Baml2006.WpfSharedBamlSchemaContext.<Create_BamlProperty_Binding_Converter>b__14c(Object target, Object value)
at System.Windows.Baml2006.WpfKnownMemberInvoker.SetValue(Object instance, Object value)
at MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(XamlMember member, Object obj, Object value)
at MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(Object inst, XamlMember property, Object value)
InnerException: