【WPF】静态属性资源绑定动态更新
1、Xaml 资源文件
<Application.Resources> <ResourceDictionary> <local:BindTest x:Key="bindtest"></local:BindTest> <SolidColorBrush x:Key="brush" Color="Blue" /> </ResourceDictionary> </Application.Resources>
其中brush是个静态资源,BindTest是个类
2、Xaml调用
<Ellipse Width="100" Height="100" Fill="{DynamicResource brush}" Grid.Row="0"></Ellipse>
//此处必须是DynamicResource
<CheckBox Margin="0,16,0,0" Content="{Binding Path=AppTest, Source={StaticResource bindtest}}" /> <CheckBox Margin="0,16,0,0" Content="{Binding Path=AppTest2, Source={StaticResource bindtest}}" />
//此处必须是StaticResource
<CheckBox Margin="0,16,0,0" Content="{x:Static local:BindTest.AppTest2}" />
//这样写也可以显示静态属性,但是不支持动态更新数据
3、BindTest 类
两种定义方法,建议使用第二种方法
public class BindTest { //方法1事件名固定和属性名一致 public static event EventHandler AppTestChanged; public static string AppTest { get { return _appTest; } set { _appTest = value; AppTestChanged?.Invoke(null, new EventArgs()); } } //方法2 推荐 事件不需要重复定义 public static string AppTest2 { get => _appTest2; set { _appTest2 = value; OnStaticPropertyChanged(new PropertyChangedEventArgs("AppTest2")); } } public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged; private static void OnStaticPropertyChanged(PropertyChangedEventArgs e) { StaticPropertyChanged?.Invoke(null, e); } private static string _appTest = "test1"; private static string _appTest2 = "test2"; }
4、修改属性
BindTest.AppTest = "666"; BindTest.AppTest2 = "777"; Application.Current.Resources["brush"] = Brushes.Red;