listview在另一个窗口中的操作时不会更新

时间:2017-10-17 03:11:46

标签: c# wpf

我的Listview没有更新我在其他窗口中发送数据的位置,但是在相同窗口中发送数据时更新。这是我的主窗口

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        CNotes.writeLn("Jacob");
    }

    private void button2_Click(object sender, RoutedEventArgs e)
    {
        Window1 spl = new Window1();
        spl.Show();
    }
}

}

这是我的窗口列表视图

public partial class Window1 : Window
    {
        ObservableCollection<Person> people = new ObservableCollection<Person();
        public Window1()
        {
            InitializeComponent();
            people.Add(new Person() { Name = "John" });
            people.Add(new Person() { Name = "Jack" });

            // Data bind to the listview,
            this.lvRcvd.ItemsSource = people;
        }

        public void writeLn(string s)
        {
            this.people.Add(new Person { Name = s });
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            this.people.Add(new Person { Name = "Jacob" });
        }
    }

    public class Person { public string Name { get; set; } }

    static public class CNotes
    {
        static Window1 fm = new Window1();
        static public void writeLn(string s)
        {
            fm.writeLn(s);
        }

    }

当我点击主窗口button1 时,listview不会更新。 但是当我点击 window1 button1 时,列表视图更新

点击主窗口按钮1 后如何在window1中更新listview?

1 个答案:

答案 0 :(得分:1)

改变这个:

static public void writeLn(string s)
    {
        fm.writeLn(s);
    }

对此:

static public void writeLn(string s)
    {
        Window1 fm = Application.OpenForms.OfType<Window1>().Take(1).SingleOrDefault();
        if (fm != null)
           fm.writeLn(s);
    }

您正在做的是创建窗体Window1的新实例,而不是访问您想要更新的打开的Window1。

编辑:

由于这是WPF,请尝试使用Application.Current。更具体地说,Application.Current.Windows