在C#
WPF
我有一个窗口,使用this.WorkingFrame.Navigate(Page1);
来托管页面
现在第1页我有一个listview
。在第1页上,您可以双击listview
中的项目以打开新窗口(第2页)来编辑项目。项目编辑后,会保存到datacontext
。现在我遇到的问题是,一旦Page2关闭,listview
就不会更新。基本上我必须离开页面并返回到它以显示更改。有没有办法从Page2刷新Page1以显示所做的更改?
这是我的代码
public partial class Page1 : Page
{
public Page1()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
//initiates the method to load data into the list view
LoadLV();
}
//Loads data into the list view object
public void LoadLV()
{
auroraDataEntities = new AuroraDataEntities();
Data data = new Data();
ObjectQuery<Inventory> inventories = auroraDataEntities.Inventories;
//Returns only objects with a quantity greater than 0, so it won't show anything you are out of
var fillList = from q in inventories
where q.Qty > 0
select q;
ingListLV.ItemsSource = fillList.ToList();
}
//Method to open what I want to be the child window basically a popup Dialog box
private void Open_Page2(object sender, RoutedEventArgs e)
{
Page2 openPage2 = new Page2();
openPage2.Show();
}
}
//This is the code for Page 2
public partial class Page2 : Window
{
public Page2()
{
InitializeComponent();
//ADDED a reference to Page1 in the constructor
Page1 page1;
}
//Method when i click the close button on the page
private void Close_Button(object sender, RoutedEventArgs e)
{
//In here is the code that I want to use to refresh the listview on page 1
//ADDED the call to the public method LoadLV on page 1
page1.LoadLV()
}
}
答案 0 :(得分:1)
问题更为普遍 - 视图可能是任意复杂的,在某处修改的数据应该在其他地方失效/刷新。假设您不仅在父子关系中有两个窗口,而且还有一个复杂的嵌套视图,带有选项卡或动态浮动窗口。显然,这不仅仅是“刷新孩子的父母”。
那么可能的方法是什么?答案是:消息, publish-subsribe 模式。你需要一个 Event Aggregator ,例如你在Prism4中有一个。聚合器允许您的视图订阅消息并发布消息。
您的案例中的消息传递架构很简单。你需要一个事件,比如
public class BusinessEntityUpdatedEvent : CompositePresentationEvent
{
public object Entity { get; set; }
//or
// if your entities share a common base class
public EntityBase Entity { get; set; }
//or
public justAnything ofAnyType { get; set; }
public orEvenMore ofAnotherType { get; set; }
}
然后您的父视图订阅该事件,您的子视图发布事件,将更新的实体传递给事件参数。
一旦你了解了应用程序不同领域之间的消息传递,你的代码就会变得更少耦合,你就会停下来思考“这两个类之间是否有联系?也许是亲子关系?”但是你开始考虑“从那里到那里应该传递什么信息?”。
修改短期解决方案是:
public class Page1
{
private void OpenPage2()
{
Page2 p = new Page2( this );
p.Show();
}
public void LoadLv() ...
}
public class Page2
{
private Page1 page1;
public Page2( Page1 page1 )
{
this.page1 = page1;
}
public void CloseButton()
{
this.page1.LoadLV();
}
}
答案 1 :(得分:0)
MainWindow mainWindow = new MainWindow();
mainWindow.Closed += (s, eventarg) =>
{
// Your method to update parent window
};
mainWindow.Show();