我正在尝试将前景色绑定到WPF文本块。
视图模型中的属性是一种颜色,如MvvvmCross文档所示:
private System.Drawing.Color _setValueColor;
public System.Drawing.Color SetValueColor
{
get { return _setValueColor == null ? System.Drawing.Color.Green : _setValueColor; }
set { SetProperty(ref _setValueColor, value); }
}
xaml文本块是
<TextBlock Grid.Column="3" Grid.Row="1" Margin="20"
Text="{Binding SetMessage}" Foreground="{Binding SetValueColor, Converter={StaticResource NativeColor}}">
</TextBlock>
我有一个资源字典resource.xaml文件,它引用了插件。插件安装为nu-get Mvvm Cross.Plugin.Color 7.1.2
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:color="clr-namespace:MvvmCross.Plugin.Color;assembly=MvvmCross.Plugin.Color"
<color:MvxNativeColorValueConverter x:Key="NativeColor" />
</ResourceDictionary>
在视图中,我在构造函数中添加资源
public SimpleReadWriteView()
{
var resourceDict = new System.Windows.ResourceDictionary();
resourceDict.Source = new Uri("Resource.xaml", UriKind.Relative);
Resources.MergedDictionaries.Add(resourceDict);
InitializeComponent();
}
当它运行时,会抛出一个强制转换错误:
InvalidCastException:无法强制转换类型为的对象"MvvmCross.Plugin.Color.MvxnativeColorValueConverter"以键入"System.Windows.Data.IValueConverter".
我还试图通过继承MvxValueConverter创建我自己的转换器,但我得到了相同类型的强制转换错误,转换器无法强制转换为System.Windows.Data.IValueConverter.
不要在WPF应用程序中使用System.Drawing.Color
,它是WinForms类型。改为使用System.Windows.Media.Color
:
private System.Windows.Media.Color setValueColor = System.Windows.Media.Colors.Green;
public System.Windows.Media.Color SetValueColor
{
get { return setValueColor; }
set { SetProperty(ref setValueColor, value); }
}
您不需要绑定转换器。您可以直接绑定SolidColorBrush
:的Color
属性
<TextBlock ... >
<TextBlock.Foreground>
<SolidColorBrush Color="{Binding SetValueColor}" />
</TextBlock.Foreground>
</TextBlock>
除此之外,从"颜色"到"画笔"的转换器看起来是这样的:
public class ColorToBrushConverter : IValueConverter
{
public object Convert(
object value, Type targetType, object parameter, CultureInfo culture)
{
return new SolidColorBrush((Color)value);
}
public object ConvertBack(
object value, Type targetType, object parameter, CultureInfo culture)
{
return ((SolidColorBrush)value).Color;
}
}