【问题标题】:Binding a textblock in Silverlight to a dependency property attribute using MVVM使用 MVVM 将 Silverlight 中的文本块绑定到依赖属性属性
【发布时间】:2012-07-11 08:45:16
【问题描述】:

我有一个在运行时填充的自定义对象类型依赖属性。它已正确更新,并且正确信息正在存储在此对象中。

但是,当我尝试将此对象的属性绑定到文本块时,没有文本出现(尽管它肯定有数据)。

所以,假设对象类型如下:

Public class CustomObject{
[Key]
 public int Id { get; set; }
 public string Name { get; set; }
 }

这个对象肯定被填充了,我已经用断点验证了这一点。

我创建了这个对象类型的依赖属性,它确实可以正常工作 - 这也已经过验证。让我们调用依赖属性 SelectedCustomObject。

我将此依赖属性绑定到我的视图:

 <TextBlock  Text="{Binding SelectedCustomObject.Name, Mode=TwoWay}" FontSize="10" VerticalAlignment="Center" HorizontalAlignment="Center"/>

DataContext 是在我的用户控件中设置的,这绝对有效,因为我已经对同一视图模型中的其他依赖项属性进行了多次绑定,并且它们运行良好。

因此,通过消除过程,我只能假设我的 XAML 语法是关闭的,并且您不能像这样绑定到我填充和工作的依赖项属性。

谁能帮我解释一下?

【问题讨论】:

    标签: silverlight xaml data-binding binding dependency-properties


    【解决方案1】:

    我的问题的答案原来是 Silverlight 维护一个单独的缓存,因此我的新依赖属性无论出于何种原因都没有加载。

    我删除并重新生成了我的 .XAP 文件,什么都没有。

    我清除了我的 IE 缓存,什么也没有。

    我从开始菜单打开 Microsoft Silverlight,转到应用程序存储选项卡并删除所有内容 - 然后刷新时,我的所有工作都出现了。

    快乐的日子。

    希望这对其他人有所帮助:)。

    【讨论】:

      【解决方案2】:

      您的Name 值很可能是在您的视图绑定到属性后设置的。正如@Erno 指出的那样,您的视图不会收到更改通知。实现INotifyPropertyChanged 将允许您的CustomObject 通知您的视图该属性已更改。

      下面是实现的样子:

      public class CustomObject : INotifyPropertyChanged
      {
          [Key]
          public int Id { get; set; }
      
          private string _name;
          public string Name
          {
              get { return _name; }
              set
              {
                  _name = value;
                  NotifyPropertyChanged("Name");
              }
          }
      
          public event PropertyChangedEventHandler PropertyChanged;
      
          protected void NotifyPropertyChanged(string info)
          {
              if (PropertyChanged != null)
              {
                  PropertyChanged(this, new PropertyChangedEventArgs(info));
              }
          }
      }
      

      【讨论】:

      • 这已经在我的实现中完成了。我正在使用 Galasoft MVVMLight 框架:)
      【解决方案3】:

      CustomClass 需要实现 INotifyPropertyChanged,以便 UI 收到更改通知

      【讨论】:

      • 是的,当设置依赖属性时,会调用它。
      猜你喜欢
      • 2011-07-29
      • 2010-12-27
      • 2014-04-10
      • 2011-07-23
      • 1970-01-01
      • 2013-03-30
      • 2016-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多