如何动态加载用户控件? [英] How do I load user controls dynamically?
问题描述
如何在窗口中动态加载用户控件(在运行时使用代码)?
How can I load a user control[s] in a window dynamically (using code at runtime)?
推荐答案
I强烈建议您查看 Prism ,因为复合用户界面正是它的用途。但是,由于这将需要您重构整个应用程序,因此我也将直接回答您的问题。
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.
如果您希望在容器中使用单个用户控件,请放置ContentControl在您的XAML中,然后设置Content属性。如果使用的是视图模型,则可以将Content绑定到视图模型上的FrameworkElement属性:
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();
如果要在列表中使用多个控件,请使用ItemsControl并将ObservableCollection<>分配给ItemsSource属性。如果使用的是视图模型,则可以将ItemsSource绑定到视图模型上的ObservableCollection属性。
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.
然后,您可以从该ObservableCollection中添加/删除视图:
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);
}
这篇关于如何动态加载用户控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!