当使用可观察的集合和单个属性时,OnPropertyChanged不会改变

时间:2016-05-12 09:55:56

标签: wpf datagrid inotifypropertychanged propertychanged

加载dataGrid并将Datagrid填充为1'

的行
public partial class MainWindow : Window
{
    public MainWindow()
    {

        InitializeComponent();
        update();
        //this.DataContext = this;



    }
    CricketEvent events = new CricketEvent();

    private void update()
    {
        events.updateList(new CricketEvent[1] { new CricketEvent(){Runs="1"} });
        DG1.ItemsSource = events.RunsList;
    }
    private void DG1_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
    {
        Window1 windowToOpen = new Window1();
        var selectedUser = this.DG1.SelectedItem;
        windowToOpen.Show();

    }
}

加载OnPropertyChanged的主类我有一个List属性和字符串属性,它调用OnPropertyChanged但我想要个人"运行"属性本身而不是整个集合。

class CricketEvent : INotifyPropertyChanged

{
    private ObservableCollection<CricketEvent> runsList;
    public string runs { get; set; }


    public CricketEvent(string numofRuns) {
        this.Runs = numofRuns;
    }
    public CricketEvent() { }

    public event PropertyChangedEventHandler PropertyChanged;

    public ObservableCollection<CricketEvent> RunsList

    {
        get { return this.runsList; }

        set
        {
            if (value != this.runsList)
            {
                this.runsList = value;
                OnPropertyChanged("RunsList");
            }
        }
    }
    public string Runs
    {
        get { return runs; }
        set
        {
            runs = value;
            // Call OnPropertyChanged whenever the property is updated
            OnPropertyChanged("Runs");
        }
    }


    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }


    public ObservableCollection<CricketEvent> updateList(CricketEvent []events)
    {
        runsList = new ObservableCollection<CricketEvent>(events.ToList()); 

        return runsList;
    }

}

这是一个更新窗口,显示一个文本框,应该更改&#34; 1s&#34;在上一个窗口中输入文本框中的内容

public partial class Window1 : Window
{

    public Window1()
    {


        InitializeComponent();
    }

    CricketEvent events = new CricketEvent();
    MainWindow main = new MainWindow();
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        events.updateList(new CricketEvent[1] { new CricketEvent(txt1.Text.ToString()) });

        main.DG1.ItemsSource = events.RunsList;

    }

1 个答案:

答案 0 :(得分:0)

Window1中的Button_Click事件不使用show的MainWindow实例 - 它创建一个新的Window实例(未显示)并将更新的列表添加到DG1.ItemsSource属性。要解决这个问题,请将Window的原始实例传递给构造函数中创建的Window1并使用它。

但是,您应该检查更新策略(和代码样式),因为有可能进行改进:

  • 如果您只想更新一个项目的一个属性,那么创建新集合并不是一个好主意。可观察集合提供更改通知,因此您根本不必重新创建集合。

  • 使用数据绑定将集合绑定到ItemsSource,而不是在代码后面添加集合。如果集合或集合中的一个项目发生更改,DataBinding将自动更新GUI元素。