gpt4 book ai didi

c# - 在 XAML 中使用样式从设置中绑定(bind) Drawing.Color

转载 作者:行者123 更新时间:2023-11-30 14:32:48 25 4
gpt4 key购买 nike

如何将设置中定义的 Color Bkg (System.Drawing.Color) 与 XAML 中的 Style 绑定(bind)?

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}}"/>

背景属性是 System.Windows.Media.Color 类型,因此需要以某种方式转换它?

最佳答案

Panel.Background属性属于 System.Windows.Media.Brush 类型而不是 System.Windows.Media.Color 因此您需要将其转换为 SolidColorBrush .您可以在下面找到这两种情况:

设置为 System.Windows.Media.Color 类型

<Setter Property="Background">
<Setter.Value>
<SolidColorBrush Color="{Binding Source={x:Static props:Settings.Default}, Path=Bkg}"/>
</Setter.Value>
</Setter>

设置为 System.Drawing.Color 类型:为此您需要自定义 IValueConverter 将其转换为 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();
}
}

您在资源中定义的:

<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}}"/>

关于c# - 在 XAML 中使用样式从设置中绑定(bind) Drawing.Color,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17833315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com