双向结合不起作用

问题描述:

我窗口的XAML:双向结合不起作用

<ListView Grid.Row="0" Name="files"> 
     <ListView.Resources> 
      <DataTemplate x:Key="CheckboxTemplate"> 
       <CheckBox IsChecked="{Binding Save, Mode=TwoWay}" /> 
      </DataTemplate> 
     </ListView.Resources> 
     <ListView.View> 
      <GridView AllowsColumnReorder="False"> 
       <GridViewColumn Header=" " Width="30" CellTemplate="{StaticResource CheckboxTemplate}" /> 
       <GridViewColumn Header="Datei" DisplayMemberBinding="{Binding File}"/> 
      </GridView> 
     </ListView.View> 
    </ListView> 

我窗口的构造函数:

IEnumerable<SaveItem> sil = sdl.Select(d => new SaveItem() { Save = true, Document = d }); 
files.ItemsSource = sil; 

和数据结构我想显示:

public class SaveItem : INotifyPropertyChanged 
{ 
    private bool save; 
    public bool Save 
    { 
     get { return this.save; } 

     set 
     { 
      if (value != this.save) 
      { 
       this.save = value; 
       NotifyPropertyChanged("Save"); 
      } 
     } 
    } 

    private void NotifyPropertyChanged(String info) 
    { 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(info)); 
     } 
    } 
    public StandardDocument Document { get; set; } 
    public string File { get { return Document.Editor.File; } } 

    #region INotifyPropertyChanged Member 

    public event PropertyChangedEventHandler PropertyChanged; 

    #endregion 
} 

我打电话给窗户。窗口出现。我取消选中listview项目的复选框。我点击一个按钮。在它的事件处理程序中,我读出了listview的itemssource,并且...未检查项的Save-Property(源代码)仍然是真的!

我的错误在哪里?为什么我的资源没有得到更新,如果我检查/取消选中复选框?

您尚未设置数据上下文。如果你全部在同一个类中 - 在窗口的构造函数中放置这样的东西。

DataContext = this; 
+0

PS评价 - 您可以使用名为“Snoop”的程序附加到正在运行的程序并检查数据绑定错误。如果你这样做 - 你会看到窗口上的数据上下文,所有的子元素可能都是空的。 – tsells 2011-12-29 02:23:34

我认为你需要将DataContext设置为后面的代码,然后为了清晰起见绑定到路径。

XAML设置窗口的DataContext

DataContext="{Binding RelativeSource={RelativeSource Self}}" 
+0

在tsells的答案背后的代码是正确的。对于我来说,如果你要在XAML中设置路径,应该在XAML中设置DataContext。 – Paparazzi 2011-12-29 02:32:40

尝试变换的IEnumerable列出.. 它不建议使用的IEnumerable作为项目源特别是当项目源使用LINQ

List<SaveItem> sil = sdl.Select(d => new SaveItem() { Save = true, Document = d }).ToList<SaveItem>(); 
files.ItemsSource = sil;