WPF: how do I load user controls dynamically?

2020-02-04 10:40发布

How can I load WPF based user control in WPF based window dynamically (using code at runtime)?

3条回答
劳资没心,怎么记你
2楼-- · 2020-02-04 11:11

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:

<UserControl x:Class="ViewA">
  ...
<UserControl/>

<UserControl x:Class="ViewB">
  ...
<UserControl/>

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.
}
查看更多
叛逆
3楼-- · 2020-02-04 11:13

I'd highly recommend having a look at Prism, since composite user interfaces is what it's for. However, since this would require you refactoring your entire application, I'll also answer your question directly.

If you want a single user control in a container, put a ContentControl in your XAML and then set the Content property. If you are using a view model, you could bind Content to a FrameworkElement property on the view model:

contentControlInstance.Content = new CustomUserControl();

If you want multiple controls in a list, use an ItemsControl and assign an ObservableCollection<> to the ItemsSource property. If you are using a view model, you could bind ItemsSource to an ObservableCollection property on the View Model.

Then you can just add/remove views from that ObservableCollection:

private ObservableCollection<FrameworkElement> views = 
    new ObservableCollection<FrameworkElement>();

private void Initialize()
{
    itemsControl.ItemsSource = views;
}

private void AddView(FrameworkElement frameworkElement)
{
    views.Add(frameworkElement);
}
查看更多
我只想做你的唯一
4楼-- · 2020-02-04 11:14

For adding multiple controls you need container.

Suppose you have a StackPanel container "myStack"

<Window ..>
    <StackPanel Name="MyStack" />
</Window>

You can create control dynamically and add it to container. See code below

void AddButtons()
{
    Button B1=new Button(),B2=new Button(), B3=new Button();
    B1.Content="Hello";
    B2.Content="First";       
    B3.content="Application";
   // Now you can set more properties like height, width, margin etc...
    MyStack.Children.Add(B1);
    MyStack.Children.Add(B2);
    MyStack.Children.Add(B2);    
}
查看更多
登录 后发表回答