【问题标题】:WPF Mainwindow closed automatically after refresh the child Usercontrol inside mainwindow刷新主窗口内的子用户控件后,WPF主窗口自动关闭
【发布时间】:2014-09-19 17:03:50
【问题描述】:

我正在开发 WPF 应用程序,它包含 MainWindow.xaml 作为容器来显示 Mainwindow 中的所有用户控件。我已经在 Mainwindow.xaml 中定义了所有菜单,并在 mainwindow.xaml 网格中显示了相应的 usercontol。

下面是我的主窗口网格定义和相应的代码隐藏事件处理程序代码

<Grid x:Name="Container" Grid.Column="0"  Width="0" Margin="0,0,0,10" Visibility="Visible">           
</Grid>

菜单点击事件处理程序背后的代码

当 maindow 在登录后加载时,它将调用并显示 CustomerListView 用户控件

private void Window_Loaded(object sender, RoutedEventArgs e)
{       
    CustomerListView CLView = new CustomerListView ();
    Container.Children.Clear();
    Container.Children.Add(CLView );
    Container.Children[0].SetValue(WidthProperty, CLView.Width);
    Container.Children[0].SetValue(HeightProperty, CLView.Height);    
}

//客户菜单点击事件

public void NewCustomer_Menu_Click(object sender, RoutedEventArgs e)
{
    //AddCustomer is User control
    AddCustomer AddEmployeeObject = new AddCustomer();

    Container.Children.Clear();
    Container.Children.Add(AddEmployeeObject);
    Container.Children[0].SetValue(WidthProperty, AddEmployeeObject.Width);
    Container.Children[0].SetValue(HeightProperty, AddEmployeeObject.Height);
}

一切正常,直到我通过新的登录控件集成我的应用程序。成功登录后,我显示了主窗口。如果我正在执行一些操作,例如添加新客户(单独的用户控件)或编辑新客户(单独的用户控件),我的应用程序会自动关闭。如何解决这个问题?

登录后显示主窗口的代码

if (IsValidUser)//Bool variable to validate user
{
    //Hide the Loginwindow
    this.Hide();
    //Display mainwindow
    MainWindow objMainWindow = new MainWindow();
    objMainWindow.ShowDialog();               
}

如果我执行任何更新或插入操作,它会在插入、更新或刷新后关闭应用程序。 似乎每次在插入或更新或尝试加载另一个用户控件或刷新主窗口网格内的用户控件后重新加载 Maindow。如何解决此问题?

【问题讨论】:

    标签: wpf xaml showdialog


    【解决方案1】:

    每次通过调用Container.Children.Clear() 添加新的客户对象时,您都会清除名为 Container 的Grid。不要在后面的代码中添加新控件,而是在 XAML 中定义您的 UI 并使用数据绑定来可视化您正在添加的对象。

    一些链接供您阅读:

    数据绑定概述:http://msdn.microsoft.com/en-us/library/ms752347(v=vs.110).aspx ObservableCollection:http://msdn.microsoft.com/en-us/library/ms668604(v=vs.110).aspx

    【讨论】:

    • 谢谢 Roel。我的应用程序中有很多用户控件。我无法在主窗口页面中定义所有内容。我需要任何临时解决方案来解决这个问题。
    【解决方案2】:

    哇哈!!!终于得到了解决方案。我已经用 IsCancel="True" 属性定义了按钮。所以当我提交数据时,它会关闭主窗口。这只是复制粘贴错误,最后删除了 IsCancel 属性并且工作正常。

    【讨论】:

      猜你喜欢
      • 2014-03-14
      • 2015-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多