c# - 双向绑定(bind)不起作用

标签 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 的项目源并且......未选中项目的保存属性(在其源代码中)仍然是正确的!

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

最佳答案

您尚未设置数据上下文。如果你们都在同一个类(class) - 在窗口的构造函数中放置类似这样的内容。

DataContext = this;

关于c# - 双向绑定(bind)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8663325/

相关文章:

c# - 从 SQL 存储过程 c# 加载输出参数

c# - 在Windows应用程序中创建一个文本文件

c# - 在 XAML 中重用路径对象

Wpf GridSplitter 替换 row.height 属性上的绑定(bind)

c# - 使用 WPF 中文本框的 KeyDown 事件捕获 Ctrl-X

c# - WPF 中的时间条目/选择器控件

c# - 加密密码

c# - aspx 页面是否有相当于 "partial class"的值?

c# - 需要用于 MS UI 自动化的源代码 dll 的代码覆盖率信息

c# - 绑定(bind)到字符串 ObservableCollection 的 DataGrid 不起作用