我有这个网格:
<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发布于 2019-04-20 00:11:45
如果你想改变许多网格上的所有背景,那么样式是另一种方法。虽然这是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}"https://stackoverflow.com/questions/55758673
复制相似问题