Bind Drawing.Color from settings with Style in XAML

走远了吗. 提交于 2019-12-10 18:18:16

问题


How to bind Color Bkg (System.Drawing.Color), defined in settings, with Style in XAML?

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 property is of type System.Windows.Media.Color, so it needs to be somehow converted?


回答1:


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:

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>

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>

and you can use it like this:

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



回答2:


As you would know that background property is of solidbrush type so its value can be set or get only with some solidbrush typw property . so what you can do is make a solidbrush type property in place of color like this..in your setting class. and now every thing just work fine..

 static SolidColorBrush brush = new SolidColorBrush(Colors.Red);

    public static SolidColorBrush colorBrush
    {
        get
        {
            return brush;
        }
    }

if you dont want to do that then you have to use value converter ..for that you can follow

this link..hope it helps you..




回答3:


Simply create a setting of type System.Windows.Media.SolidColorBrush.

Select Browse... from the Type ComboBox of the new setting, then select PresentationCore -> System.Windows.Media -> SolidColorBrush.

You may now directly use that setting as you already did:

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


来源:https://stackoverflow.com/questions/17833315/bind-drawing-color-from-settings-with-style-in-xaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!