从XAML中的样式的设置绑定Drawing.Color [英] Bind Drawing.Color from settings with Style in XAML

查看:445
本文介绍了从XAML中的样式的设置绑定Drawing.Color的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用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?

推荐答案

Panel.Background 属性是 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆