c# - 如何使用 MVVM 模式在 WPF 中动态绑定 UserControl
问题描述
目前我正在一个 WPF MVVM 应用程序中工作,我想在其中使用 ItemsControl 在 MainWindow.xaml 中显示 UserControl。根据要求,我必须通过管理 ViewModel 中的一些条件来切换或绑定不同的用户控件。正如我在下面的代码中提到的,应该绑定 UserControl。但目前的问题是它的静态和完美的工作。但我无法根据条件更改它。那么有什么东西可以从 ViewModel 更改运行时的 UserControlColumn1XL 吗?提前致谢。
<StackPanel Grid.Column="0" Background="Black" VerticalAlignment="Top" >
<ItemsControl ItemsSource="{Binding NormalCollection}" Name="ListNormal" Margin="4,0" >
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel HorizontalAlignment="Left" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<!--<This below line should be dynamically change through MVVM code>-->
<controls:UserControlColumn1XL HorizontalAlignment="Left" Margin="2" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
解决方案
您通常使用 DataTemplates 执行此操作。从 ViewModel 中的 an 开始ObservableCollection<object> Objects
...不一定是<object>
,如果您愿意,它可以是一些常见的基类。然后在您的 XAML 中为每种类型添加 DataTemplates。我将它们放在ItemsControl.Resources
这里,但您可以将它们放入UserControl.Resources
或任何您认为合适的地方:
<ItemsControl>
<ItemsControl.Resources>
<DataTemplate DataType="{x:Type viewmodels:YourViewModel1}">
<views:UserControl1 />
</DataTemplate>
<DataTemplate DataType="{x:Type viewmodels:YourViewModel2}">
<views:UserControl2 />
</DataTemplate>
... etc ...
还要删除<ItemsControl.ItemTemplate>
标签,因为如果你不这样做,它只会覆盖 DataTemplates。
这就是你需要做的!每次有一个类型的对象时YourViewModel1
,Objects
它都会与 UserControl1 一起显示,并且对于您指定的所有其他模板也是如此。
推荐阅读
- python - 使用 PyPDF2 的 PDFFileReader 打开 PDF 文件时抛出错误
- javascript - 仅收听当前数据的 Firebase Firestore 数据更改?
- php - Codeigniter restful 简单的 api 花费太多时间
- javascript - 通过键从数组中删除没有引用的对象
- authentication - 登录屏幕上的跳过按钮应导致主屏幕,但它无法正常工作
- php - 是否足以防止 SQL 注入?
- reactjs - Firebase 规则检查现有资源数据但返回权限被拒绝
- mac-catalyst - performSegue EXC_BAD_ACCESS 仅在 MacCatalyst 上崩溃 - Xcode 12.5.1
- android - Alt+Enter 时自动导入 NonNull 和 NotNull
- python - 如果 number 为 3 且 sum 包含 3,则返回 True 语句