【问题标题】:Unable to get DataGrid working with ObservableCollection无法让 DataGrid 与 ObservableCollection 一起工作
【发布时间】:2011-04-25 03:38:56
【问题描述】:

一切都会编译,但在运行时会显示一个空白行。如果我尝试编辑一个条目,它会显示“未设置 XPath”。我究竟做错了什么?我尝试了很多变体,没有 INotifyPropertyChanged 接口等。

基类是:

public class Variable : INotifyPropertyChanged 
    {
        public string Name;
        public string Value;

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
    }

可观察的集合是:

 public class VariableCollection:ObservableCollection<Variable>
    {
         public VariableCollection()
            : base()
        {
        }

         public VariableCollection(List<Variable> list)
            : base(list)
        {
        }
    }

绑定是:

public VariablesView(VariableCollection variables)
        {
            InitializeComponent();

            gridContent.ItemsSource = variables;
        }   

XAML 是:

<DataGrid Name="gridContent" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding Name}" Header="Name" />
                <DataGridTextColumn Binding="{Binding Value}" Header="Value" />
            </DataGrid.Columns>
        </DataGrid>

【问题讨论】:

    标签: wpf datagrid observablecollection


    【解决方案1】:

    这很简单。您的类中有字段而不是属性。

    将代码改为:

        public string Name{ get; set;}
        public string Value{ get; set;}
    

    【讨论】:

    • 天啊,我只浪费了四个小时。谢谢!
    • 我在我的代码中多次使用getter setter,但这次我错过了。非常感谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-29
    • 2014-11-22
    • 2014-05-15
    • 2010-10-16
    • 2019-11-27
    • 2017-02-12
    • 1970-01-01
    相关资源
    最近更新 更多