【发布时间】:2013-06-18 09:42:06
【问题描述】:
我已经挠头 2 天了。虽然我是 .NET 的新手,但我已经阅读了 20 多个帖子和问题,我认为我的代码应该可以工作。有些请投光。
XAML:
<TextBox Grid.Column="3" Name="testgrid" Text="{Binding textsource, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"></TextBox>
后面的代码:
public MainWindow()
{
InitializeComponent();
textbind tb = new textbind();
tb.textsource = "one"; //one is displayed in the textbox.
testgrid.DataContext = tb;
}
还有:
public class textbind : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
private string a=string.Empty;
public textbind()
{
}
public string textsource
{
get { return a; }
set
{
if (value != a)
{
a = value;
NotifyPropertyChanged(textsource);
}
}
}
}
改变属性:
public class changevalue
{
//code doing things. this class is initialized by some other processes.
textbind tb1 = new textbind();
tb1.textsource = "two"; // no updates to two in the text box.
}
我相信每次我更改 textsource 属性时,它都会反映文本框中的更改,但它不会发生。索内恩请帮忙。
谢谢。
【问题讨论】:
-
它不会解决特定问题,但您应该真正将 NotifyPropertyChanged 更改为
var handler = PropertyChanged; if (handler!=null) { handler(this, new PropertyChangedEventArgs(info));}以帮助避免 PropertyChanged 在测试和执行之间可能变为 null 的线程问题。 -
我敢打赌,如果您查看“输出”窗口,您会在启动应用程序或更新值时看到绑定错误。这只是 HB 所说的更好的表达方式。
标签: c# .net wpf .net-4.0 inotifypropertychanged