我是WPF的新手,并尝试了一个简单的数据绑定示例,但它不起作用.我的窗口有一个TextBlock,它绑定到window对象的一个属性.我在代码中声明了该属性.
运行此时,我看到TextBlock中出现正确的值.还有一个按钮,点击它时会更新属性,但我没有看到这会影响TextBlock.
我已经正确地实现了INotifyPropertyChanged,我能够确定.我还看到,在调试时,有些东西订阅了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>
Run Code Online (Sandbox Code Playgroud)
窗口类中的代码是:
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));
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题在于你的"TheName"属性设置器.OnPropertyChanged方法调用传递"thename" 的值,而不是"thename"的"名称".(对不起,如果这没有意义 - 用于示例的变量名称与我们密谋!)
正确的代码是:
string thename;
public string TheName
{
get { return thename; }
set { thename = value; OnPropertyChanged("TheName"); }
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!