How do I load user controls dynamically?

后端 未结 3 1214
清酒与你
清酒与你 2020-12-09 11:00

How can I load a user control[s] in a window dynamically (using code at runtime)?

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-09 11:34

    Or use binding. Here's a really crude example showing how different WPF controls can be shown in a single WPF window using ContentControl and binding (which is what a toolkit like Prism or Caliburn Micro does).

    XAML:

    
      ...
    
    
    
      ...
    
    

    Code:

    void ShowViewModelDialog (object viewModel)
    {
      var host = new MyViewHost();
      FrameworkElement control = null;
      string viewModelName = viewModel.GetType().Name;
      switch (viewModelName )
      {
         case ("ViewModelA"):
           control  = new ViewA();
           break;
         case ("ViewModelB"):
           control  = new ViewB();
           break;
         default:
           control = new TextBlock {Text = String.Format ("No view for {0}", viewModelName);
           break;
      }
    
      if (control!=null) control.DataContext = viewModel;
      host.DataContext = control;
      host.Show(); // Host window will show either ViewA, ViewB, or TextBlock.
    }
    

提交回复
热议问题