通知列表wpf .net4.0中的更改

时间:2011-01-07 09:41:28

标签: c# xaml datagrid .net-4.0 inotifypropertychanged

我正在尝试将项目广告到如下所示的列表,并更新DataGrid,但似乎我遗漏了一些东西,我应该通知哪个属性?

C#

public partial class Window8 : INotifyPropertyChanged
    {
        public TestObj TestObject { get; set; }
        public int Count { get; set; }

        public Window8()
        {
            InitializeComponent();
            DataContext = this;

            var newList = new List<Test>();

            newList.Add(new Test{I = 1, S = "Test"});
            TestObject = new TestObj { S = "Testing object", List = newList };

            Count = TestObject.List.Count;
        }


        private ICommand _addItemCommand;
        public ICommand AddItemCommand
        {
            get
            {
                if (_addItemCommand == null)
                    _addItemCommand = new RelayCommand(n =>
                                                           {
                                                               TestObject.List.Add(new Test {I = 1, S = "New object"});
                                                               Count = TestObject.List.Count;

                                                               NotifyPropertyChanged("TestObject");
                                                               //NotifyPropertyChanged("TestObject.List");

                                                               NotifyPropertyChanged("Count");

                                                           });
                return _addItemCommand;
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;


        protected void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public class TestObj
    {
        public string S { get; set; }
        public List<Test> List { get; set; }
    }

    public class Test
    {
        public string S { get; set; }
        public int I { get; set; }
    }

XAML

<StackPanel>
        <Button Height="23" Width="100" Command="{Binding Path=AddItemCommand}" >Add Item</Button>
        <DataGrid Height="100" ItemsSource="{Binding Path=TestObject.List}" IsReadOnly="True" />
 <TextBlock Text="{Binding Path=Count}" />

当我按下按钮时,我在列表中添加对象,计数器会计数,但列表中没有任何反应。         

2 个答案:

答案 0 :(得分:3)

您应该使用ObservableCollection而不是List

代码应该是 -

public Window8()
{
    InitializeComponent();
    DataContext = this;

    var newList = new ObservableCollection<Test>();

    newList.Add(new Test { I = 1, S = "Test" });
    TestObject = new TestObj { S = "Testing object", List = newList };

    Count = TestObject.List.Count;
}

public class TestObj
{

    public string S { get; set; }
    public ObservableCollection<Test> List { get; set; }
}

还应在不在窗口中的对象上实现INotifyPropertyChanged

答案 1 :(得分:0)

你'对象'必须实现INotifyPropertyChanged,而不是表单或窗口。