【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;
标签:
WPF
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
2016-05-09 【转】【C#】判断两个文件是否相同
2014-05-09 【Asp.Net】document.getElementById 的属性介绍