开发者

Silverlight DataContext Databinding behavior

开发者 https://www.devze.com 2023-04-09 05:05 出处:网络
I\'ll start off with a stripped-down/sanitized version of my code: Model: class DataObj : INotifyPropertyChanged {

I'll start off with a stripped-down/sanitized version of my code:

Model:

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

View:

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

View code-behind:

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

Now, my question 开发者_如何学Cis, if the DataItems list is initialized but empty, what is the expected behavior when something tries to bind to, say, the first element in the list? My understanding is that it just ignores the binding; is that true?


Yes it will ignore the binding. If subsequently an item is added to the empty list the text blocks will not update since the binding expression associated with them will not know that the change happened.

The appropriate solution is to use:

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

Additions to the collection will notify "Item[]" has changed which will allow the binding expression to re-evaluate.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号