【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;

 

posted on   梦琪小生  阅读(136)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 阿里最新开源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 的属性介绍
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示