【问题标题】:WPF Binding Label Content to PropertyWPF 将标签内容绑定到属性
【发布时间】:2015-04-23 07:14:16
【问题描述】:

我已经阅读了几篇关于此的文章,但似乎无法在我的属性更改时更新我的​​标签。 PropertyChanged 事件正在触发,并且属性正在更新为新文本,但标签未更新。 感谢您的帮助!

XAML

 <Grid.Resources>
     <c:UserInformation x:Key="myTaskData"/>
 </Grid.Resources>
 <Label Name="lblTaskNameTitle" Content="{Binding Path=propTaskName, UpdateSourceTrigger=PropertyChanged}"/>

窗口

 UserInformation t = new UserInformation();                

 t.propTaskName = "Updated Task Name";
 this.DataContext = t.propTaskName;

代码背后

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));  
            }
        }

更新以反映评论建议。

【问题讨论】:

  • 你在哪里设置myTaskData?看起来应该是你的DataContext 而不是任务名称。
  • myTaskData 在 Grid.Resources 部分中设置。

标签: c# wpf


【解决方案1】:

Xaml 应该是:

<Label Name="lblTaskNameTitle" Content="{Binding Path=propTaskName, UpdateSourceTrigger=PropertyChanged}"/>

UserInformation t = new UserInformation();               
t.propTaskName = "Updated Task Name";
this.DataContext = t;

【讨论】:

  • 我已更新 xaml 以反映这一点,但标签仍未更新?其他建议?
【解决方案2】:

绑定查看 DataContext,而不是背后的代码。您可以通过在后面的代码中添加 DataContext = this 来使它们相同,尽管您希望使用单独的类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-20
    • 2017-01-07
    • 1970-01-01
    • 2013-02-18
    • 1970-01-01
    • 1970-01-01
    • 2013-06-18
    • 1970-01-01
    相关资源
    最近更新 更多