TwoWay-Binding不起作用

时间:2011-12-29 02:13:37

标签: c# .net wpf binding

我窗口的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仍然是真的!

我的错误在哪里?如果选中/取消选中复选框,为什么我的来源不会更新?

3 个答案:

答案 0 :(得分:2)

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

DataContext = this;

答案 1 :(得分:0)

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

XAML设置Window DataContext

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

答案 2 :(得分:0)

尝试将IEnumerable转换为列表.. 不建议使用IEnumerable作为项目源,特别是当使用Linq评估项目源时

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