双向绑定不能工作

本文关键字:工作 不能 绑定 | 更新日期: 2023-09-27 18:18:55

my window的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>

我的Window的构造函数:

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
}

我调用窗口。窗口出现。取消选中列表视图中某项的复选框。我点击一个按钮。在它的事件处理程序中,我读出列表视图的itemssource和…未检查项的保存属性(在其源代码中)仍然为真!

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

双向绑定不能工作

您还没有设置数据上下文。如果您都在同一个类中-在窗口的构造函数中添加类似的内容。

DataContext = this;

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

XAML设置Window DataContext

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

尝试将IEnumerable转换为list..不建议使用IEnumerable作为项目源,特别是当项目源使用Linq

进行评估时。
List<SaveItem> sil = sdl.Select(d => new SaveItem() { Save = true, Document = d }).ToList<SaveItem>();
files.ItemsSource = sil;