【发布时间】:2009-05-16 16:57:27
【问题描述】:
我是 WPF 新手,正在尝试一个简单的数据绑定示例,但它不起作用。 我的窗口有一个 TextBlock,我将它绑定到窗口对象的一个属性。 我在代码中声明了该属性。
运行此程序时,我看到 TextBlock 中出现了正确的值。 还有一个按钮,单击该按钮会更新属性,但我没有看到这会影响 TextBlock。
据我所知,我正确实施了 INotifyPropertyChanged。我还看到,在调试时,something 订阅了 PropertyChanged 事件,但它似乎没有做任何事情。
我有两个问题:
1) 为什么没有按预期工作?
2) 是否有任何简单的方法可以在运行时调试导致这种情况的原因,而无需借助第三方工具?根据我粗略的了解,在我看来,WPF 中的调试支持非常缺乏。
XAML 是(不包括“标准”XAML 窗口元素):
<TextBlock Height="28" Name="label1" VerticalAlignment="Top"
Text="{Binding Path=TheName}"
Grid.Row="0"
></TextBlock>
<Button Height="23" Name="button1" VerticalAlignment="Stretch" Grid.Row="1"
Click="button1_Click">
Button
</Button>
window类中的代码是:
public partial class Window1 : Window
{
protected MyDataSource TheSource { get; set; }
public Window1()
{
InitializeComponent();
TheSource = new MyDataSource();
TheSource.TheName = "Original"; // This works
this.label1.DataContext = this.TheSource;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
TheSource.TheName = "Changed"; // This doesn't work
}
}
public class MyDataSource : INotifyPropertyChanged
{
string thename;
public string TheName
{
get { return thename; }
set { thename = value; OnPropertyChanged(thename); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
}
【问题讨论】:
标签: wpf data-binding xaml