【发布时间】:2019-09-30 00:20:56
【问题描述】:
我尝试将文本块用户控件与我的类的属性绑定,但它只在初始阶段有效,我已经在我的类中实现了 IPropertyChnaged。
在我的课堂上,_Feedbackpos(属性字段)会在后台发生变化,我不知道如何解决这个问题。
我的班级
public class TestControl : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyname)
{
if(PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyname));
}
}
private double _Feedbackpos;
public double Feedbackpos
{
get
{
return _Feedbackpos;
}
set
{
_Feedbackpos = value;
NotifyPropertyChanged("Feedbackpos");
}
}
//it's a callback function, it would excute when detect feedback position of controller change
private void ReadFeedbackpos()
{
_Feedbackpos = Controller.Read();
}
}
应用程序窗口
TestControl TestDll = new TestControl();
Binding BindingTxtBlk = new Binding(){Source= TestDll, Path = new Property("Feedbackpos")};
FeedbackPosTxtBlk.Setbinding(Textblock.TextProperty,BindingTxtBlk);
【问题讨论】:
-
"但它只在初始阶段有效"请定义此语句
-
如果您希望引发属性更改事件,您应该使用属性
Feedbackpos来设置值,而不是字段。 -
好吧,如果你不调用
Property的Setter,你怎么期望Setter中的代码会被执行? -
仅供参考 -
NotifyPropertyChanged("Feedbackpos");不仅限于在Setter内调用,您可以在任何地方调用它,因此您可以通过简单地调用NotifyPropertyChanged("Feedbackpos");来扩展您的ReadFeedbackpos -
C#中没有魔法。如果你不打电话给PropertyChanged(this, new PropertyChangedEventArgs(propertyname));-PropertyChanged事件将不会发生。
标签: c# wpf properties field