【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;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值