【问题标题】:Add UserControl in MainWindow from another UserControl从另一个 UserControl 在 MainWindow 中添加 UserControl
【发布时间】:2014-09-23 02:43:08
【问题描述】:

我在 UserControl_1 中有两个 UserControl,有一个按钮可以在 MainWindow.axml 中的 StackPanel 中添加 UserControl_2。我在 UserControl_1 中执行以下操作:

private void Button_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    UserControl_2 uc = new UserControl_2();

    ((MainWindow)Application.Current.MainWindow).stackpanel_2.Children.Add(uc);
}

如何在 MVVM 模式中做到这一点?

【问题讨论】:

    标签: c# wpf mvvm user-controls


    【解决方案1】:

    简短的回答是,您不要对 MVVM 执行此操作。

    在 MVVM 中,您的视图是视图模型中包含的数据的可视化表示。您永远不会直接添加控件,因为它不会代表任何数据!

    如果您的视图上有一个ItemsControl,该ItemsControl 绑定到视图模型中的一个集合,那么向该集合添加一个项目将添加适当的控件。这就是您将如何实现现有代码在 MVVM 中的精神。

    【讨论】:

      猜你喜欢
      • 2017-08-03
      • 2019-09-05
      • 1970-01-01
      • 1970-01-01
      • 2021-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-17
      相关资源
      最近更新 更多