首页 > 解决方案 > WPF 绑定背景为 SolidColorBrush

问题描述

我有这个网格:

    <Grid x:Name="topGrid"  Height="100" VerticalAlignment="Top" Margin="10,0,0,0" />

在我的代码中,如果我这样设置背景:

topGrid.Background = "#FF3C3C3C".ToBrush()

使用这个扩展:

Module Extensions
<Extension()>
Function ToBrush(ByVal HexColorString As String) As SolidColorBrush
    Return CType((New BrushConverter().ConvertFrom(HexColorString)), 
SolidColorBrush)
End Function
End Module 

我可以很好地更改背景,但是我的表单上有大约 20 个网格,我想使用绑定一次更改所有网格的背景。

我试过这样做:

这是xml:

 <Grid x:Name="topGrid" Background="{Binding MyBackgroundColor}" Height="100" VerticalAlignment="Top" Margin="10,0,0,0" >

这是代码:

    Private Sub button1_Click(sender As Object, e As RoutedEventArgs) Handles button1.Click
    MyBackgroundColor = "#FF3C3C3C".ToBrush()
End Sub
Private _myBackgroundColor As SolidColorBrush
Public Property MyBackgroundColor() As SolidColorBrush
    Get
        Return _myBackgroundColor
    End Get
    Set
        _myBackgroundColor = Value
    End Set
End Property

Public Sub New()
    InitializeComponent()
End Sub

标签: wpfvb.net

解决方案


如果您想更改许多网格上的所有背景,那么样式是另一种方法。虽然这是 c#,但代码很少,您可以通过在线转换器运行它。

为了快速起见,我在 app.xaml 中完成了此操作,但您希望将其放入合适的应用程序中合并到 app.xaml 中的资源字典中。

<Application.Resources>
    <SolidColorBrush x:Key="gridBackgroundBrush" Color="Blue"/>
    <Style TargetType="{x:Type Grid}">
        <Setter Property="Background" Value="{DynamicResource gridBackgroundBrush}"/>
    </Style>
</Application.Resources>
</Application>

你可以改变那个画笔:

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        Color colour = (Color)ColorConverter.ConvertFromString("#FFD700");
        Application.Current.Resources["gridBackgroundBrush"] = new SolidColorBrush(colour);
    }

如果您不希望一两个网格具有这种行为,您可以将它们的背景设置为白色或透明,这将优先于样式。

如果您的要求更复杂,那么您可能会丢失样式,而是直接将资源用作 DynamicResource。这可能是克莱门斯的意思。

 <Grid Background="{DynamicResource gridBackgroundBrush}"

推荐阅读