wpf - 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
解决方案
如果您想更改许多网格上的所有背景,那么样式是另一种方法。虽然这是 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}"
推荐阅读
- office365 - 将文本输入添加到图库项目
- django-forms - Django 分组选择字段迭代
- javascript - 如何在我的 Angular 项目中设计包含播放列表的视频播放器?
- jenkins - 将用户名和密码传递给Dimensions-Jenkins 作业
- kubernetes - 如何从 POD 中的另一个容器获取 Envoy (istio-proxy) 容器的 CPU 使用率
- vue.js - 在单击 vue 的按钮上如何从 vue-bootstrap-dropdown 关闭 Dropdown?
- javascript - Angular NGXS TypeError:无法冻结
- php - 一位数的正则表达式捕获两位数?
- ios - JSON序列化期间的快速错误:无法读取数据,因为它的格式不正确
- javascript - 如何在反应中创建全局数组?当我对每个索引进行单独操作时,我希望它们将它们保存在一个数组中