WPF 将标签内容绑定到属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29802088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF Binding Label Content to Property
提问by Litmas
I have read several articles about this and can't quite seem to get my label to update when my property is changed. The PropertyChanged event is firing, and the property is updating to the new text but the label is not updating. Thanks for the help!
我已经阅读了几篇关于此的文章,但似乎无法在我的属性更改时更新我的标签。PropertyChanged 事件正在触发,属性正在更新为新文本,但标签未更新。谢谢您的帮助!
XAML
XAML
<Grid.Resources>
<c:UserInformation x:Key="myTaskData"/>
</Grid.Resources>
<Label Name="lblTaskNameTitle" Content="{Binding Path=propTaskName, UpdateSourceTrigger=PropertyChanged}"/>
Window
窗户
UserInformation t = new UserInformation();
t.propTaskName = "Updated Task Name";
this.DataContext = t.propTaskName;
Code Behind
背后的代码
class UserInformation : INotifyPropertyChanged
{
private string strTaskName = "Task Name: ";
public string propTaskName
{
get { return this.strTaskName; }
set
{
this.strTaskName = value;
NotifyPropertyChanged("propTaskName"); //Call the method to set off the PropertyChanged event.
}
}
//INotifyPropertyChanged stuff
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
Updated to reflect comment suggestions.
更新以反映评论建议。
回答by HungDL
Xaml should be:
Xaml 应该是:
<Label Name="lblTaskNameTitle" Content="{Binding Path=propTaskName, UpdateSourceTrigger=PropertyChanged}"/>
UserInformation t = new UserInformation();
t.propTaskName = "Updated Task Name";
this.DataContext = t;
回答by Owen Johnson
Bindings look at the DataContext, not the code behind. You can make them the same thing by adding DataContext = this to your code behind, although you would want to use a separate class.
绑定着眼于 DataContext,而不是背后的代码。您可以通过将 DataContext = this 添加到您的代码后面来使它们成为相同的东西,尽管您希望使用单独的类。

