WPF MVVM Binding dynamic control in code behind and pass in View

不想你离开。 提交于 2019-12-02 13:15:05

There are two ways to solve this, one involves setting the template based on your data type (DataTemplates) and the second involves setting it based on the data itself (DataTriggers).

In the first case your LowCollection should be an array of objects, or some base class that your view models are all derived from (ViewModel1, ViewModel2 etc). In this case you can get rid of your itemtemplate altogether and just add DataTemplates to specify how each of the items in your ItemsControl should be represented:

<ItemsControl.Resources>

    <DataTemplate DataType="{x:Type local:ViewModel1}">
        <UserControl1 />
    </DataTemplate>

    <DataTemplate DataType="{x:Type local:ViewModel2}">
        <UserControl2 />
    </DataTemplate>

    ... etc...

In the second case you need to set a template based on the value of some property in your view model. In this case you do need to set the ItemTemplate, and you give it a Style which uses data triggers to set an appropriate DataTemplate:

    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <ContentPresenter Content="{Binding}">
                <ContentPresenter.Style>
                    <Style TargetType="{x:Type ContentPresenter}">
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding YourProperty}" Value="YourValue1">
                                <Setter Property="ContentTemplate" Value="{StaticResource YourDataTemplate1}" />
                            </DataTrigger>
                            <DataTrigger Binding="{Binding YourProperty}" Value="YourValue2">
                                <Setter Property="ContentTemplate" Value="{StaticResource YourDataTemplate2}" />
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </ContentPresenter.Style>
            </ContentPresenter>
        </DataTemplate>
    </ItemsControl.ItemTemplate>

The relevant parts to note here are that there is a property in your view model called YourProperty which can have two values i.e. YourValue1 or YourValue2; the style above then selects either YourDataTemplate1 or YourDataTemplate2, depending on the value of YourProperty.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!