问题描述
如何使用XAML中的样式来绑定在设置中定义的颜色 Bkg (System.Drawing.Color)?
How to bind Color Bkg (System.Drawing.Color), defined in settings, with Style in XAML?
xmlns:props =clr-namespace:App.Properties
xmlns:props="clr-namespace:App.Properties"
<Style TargetType="{x:Type StackPanel}" x:Key="_itemStyle">
<Setter Property="Background" Value="{Binding Path=Bkg, Source={x:Static props:Settings.Default}}"/>
Background属性是System.Windows.Media.Color类型,因此需要进行某种转换?
Background property is of type System.Windows.Media.Color, so it needs to be somehow converted?
推荐答案
属性是 System.Windows.Media。刷
类型而不是 System.Windows.Media.Color
,因此您需要将其转换为 SolidColorBrush
。您可以在下面找到两种情况:
Panel.Background
property is of a System.Windows.Media.Brush
type and not System.Windows.Media.Color
therefore you need to convert it into SolidColorBrush
. Below you can find both case scenarios:
设置为 System.Windows.Media.Color
Setting is of System.Windows.Media.Color
type
<Setter Property="Background">
<Setter.Value>
<SolidColorBrush Color="{Binding Source={x:Static props:Settings.Default}, Path=Bkg}"/>
</Setter.Value>
</Setter>
设置为 System.Drawing.Color
type :为此,您需要自定义 IValueConverter
将其转换为 SolidColorBrush
:
Setting is of System.Drawing.Color
type: for this you need custom IValueConverter
to convert it into SolidColorBrush
:
public class ColorToBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var dc = (System.Drawing.Color)value;
return new SolidColorBrush(new Color { A = dc.A, R = dc.R, G = dc.G, B = dc.B });
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
which you define in your resources:
<Window.Resources>
<local:ColorToBrushConverter x:Key="ColorToBrushConverter"/>
</Window.Resources>
,您可以这样使用:
<Setter Property="Background" Value="{Binding Source={x:Static props:Settings.Default}, Path=Bkg, Converter={StaticResource ColorToBrushConverter}}"/>
这篇关于从XAML中的样式的设置绑定Drawing.Color的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!