【问题标题】:Silverlight DataContext Databinding behaviorSilverlight DataContext 数据绑定行为
【发布时间】:2011-11-28 02:11:57
【问题描述】:

我将从我的代码的精简/净化版本开始:

型号:

class DataObj : INotifyPropertyChanged {
    // these actually call OnPropertyChanged, and have associated private variables
    public string Name { get; set; }
    public int Age { get; set; }
}

class DataContextObj : INotifyPropertyChanged {
    public List<DataObj> DataItems { get; set; }
}

查看:

<StackPanel x:Name="MyPanel">
    <TextBlock Text="{Binding Path=DataItems[0].Name}" />
    <TextBlock Text="{Binding Path=DataItems[0].Age}" />
</StackPanel>

查看代码隐藏:

//in the constructor
MyPanel.DataContext = new DataContextObj();

现在,我的问题是,如果 DataItems 列表已初始化但为空,那么当某些内容尝试绑定到(例如)列表中的第一个元素时,预期的行为是什么?我的理解是它只是忽略了绑定;这是真的吗?

【问题讨论】:

    标签: silverlight data-binding datacontext


    【解决方案1】:

    是的,它会忽略绑定。如果随后将一个项目添加到空列表中,则文本块将不会更新,因为与它们关联的绑定表达式不会知道发生了更改。

    适当的解决方案是使用:

      public class DataContextObj
      {
            public ObservableCollection<DataObj> DataItems {get; private set; }
      }
    

    对集合的添加将通知“Item[]”已更改,这将允许重新评估绑定表达式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-30
      • 2011-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多