Pat*_*vic 3 c# wpf settings bind colors
如何将设置中定义的Color Bkg(System.Drawing.Color)与XAML中的Style 绑定?
的xmlns:道具= "CLR的命名空间:App.Properties"
<Style TargetType="{x:Type StackPanel}" x:Key="_itemStyle">
<Setter Property="Background" Value="{Binding Path=Bkg, Source={x:Static props:Settings.Default}}"/>
Run Code Online (Sandbox Code Playgroud)
Background属性是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>
Run Code Online (Sandbox Code Playgroud)
设置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();
}
}
Run Code Online (Sandbox Code Playgroud)
您在资源中定义的:
<Window.Resources>
<local:ColorToBrushConverter x:Key="ColorToBrushConverter"/>
</Window.Resources>
Run Code Online (Sandbox Code Playgroud)
你可以像这样使用它:
<Setter Property="Background" Value="{Binding Source={x:Static props:Settings.Default}, Path=Bkg, Converter={StaticResource ColorToBrushConverter}}"/>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2365 次 |
| 最近记录: |