DependencyProperty数据绑定 [英] DependencyProperty data binding

查看:72
本文介绍了DependencyProperty数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好!

我尝试将UI绑定到自定义DependencyProperty:

Hello!

I try to bind my UI to custom DependencyProperty:

...

<window.resources>
    <local:localization x:key="Localization" xmlns:x="#unknown" xmlns:local="#unknown"></local:localization>
</window.resources>
    <grid name="mainStack" datacontext="{StaticResource Localization}">
         <Button Padding="10,3" Margin="5" Content="{Binding Path=BtnAdd}"   Command="New"/>
    </grid>



我也有本地化"课程:



Also I have class "Localization":

class Localization : DependencyObject, INotifyPropertyChanged
    {
        public static DependencyProperty BtnAddProperty;
        
        static Localization()
        {
            BtnAddProperty = DependencyProperty.Register("BtnAdd", typeof(string), typeof(Localization));
            
        }

        public string BtnAdd
        {
            set
            {
                SetValue(BtnAddProperty, value);
            }
            get
            {
                return (string)GetValue(BtnAddProperty);
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                PropertyChangedEventArgs e = new PropertyChangedEventArgs(propertyName);
                handler.Invoke(this, e);
            }
        }

        public Localization()
        {
            BtnAdd = MainWindowRes.BtnAdd;
        }

        public void SwitchLanguage()
        {
            BtnAdd = MainWindowRes.BtnAdd;
            OnPropertyChanged("BtnAdd");
        }
       
    }



第一次我的UI元素获得我的属性值.但是,当我使用方法SwitchLanguage()时,属性会获取新数据,并且UI仍然是第一个值.

有人可以帮我吗?

P.S.
抱歉,我的英语.

Eugene



First time my UI element gets my property value. But when I use my method SwitchLanguage(), property gets new data, and UI still have first value.

Can someone help me please?

P.S.
Sorry, for my English.

Eugene

推荐答案

 BtnAddProperty = DependencyProperty.Register("BtnAdd", typeof(string), typeof(Localization),new FrameworkPropertyMetadata(new PropertyChangedCallback(OnBtnAddPropertyChanged)));
...
private static void OnBtnAddPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
Button btn = o as Button;
... //some localization on button content
btn.OnPropertyChanged(e.Property.Name);
...
}



希望这行得通.



hope this works.


这篇关于DependencyProperty数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆