首页 > 解决方案 > 如何使用 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>

标签: c#wpfmvvm

解决方案


您通常使用 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。

这就是你需要做的!每次有一个类型的对象时YourViewModel1Objects它都会与 UserControl1 一起显示,并且对于您指定的所有其他模板也是如此。


推荐阅读