使用 ItemTemplating 更改网格的内容

Changing the content of a grid using ItemTemplating

现状

我有网格,这个网格有 3 行。每行包含我的一个用户控件。每个 UserControl 都硬编码到网格行之一:

 <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>

<Grid>
    <local:myUserControl DependencyProperty1 = "{Binding Property1}" DependencyProperty2 = "{Binding Property2}" />
    <Stackpanel><Button/><Combobox/></StackPanel>
</Grid>
<Grid Grid.Row="1">
    <local:myUserControl DependencyProperty1 = "{Binding Property1}" DependencyProperty2 = "{Binding Property2}" />
    <Stackpanel><Button/><Combobox/></StackPanel>
</Grid>

[...]

</Grid>

我的任务

我的控件多于我 Window 所能容纳的。我想允许用户通过在 ComboBox 中选择他喜欢的控件然后按 Button.

来在所有可用控件之间切换

我想过使用 ItemTemplating 来完成这个。我发现 this post 关于如何处理不同类型的数据类型,这很有帮助。但是我觉得这里的列表有点多余,因为其中总是只有一个 Item ,但我不知道该用什么代替。

我的问题

是否有更好的解决方案,因为使用只有一个项目的列表,或者是否有更好的方法来创建 'swappable' 控件?

这里的代码将实现一个控件,其内容根据组合框的值而变化。这只使用了省略号,但如果需要,您可以将自己的用户控件插入到 ContentControl 中:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <ComboBox Name="MyComboBox">
        <ComboBoxItem Content="Fish"/>
        <ComboBoxItem Content="Chips"/>
    </ComboBox>

    <Grid Grid.Row="1">
        <ContentControl>
            <ContentControl.Style>
                <Style TargetType="ContentControl">
                    <Setter Property="Content">
                        <Setter.Value>
                            <Ellipse Fill="Green" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
                        </Setter.Value>
                    </Setter>
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding ElementName=MyComboBox, Path=SelectedItem.Content}" Value="Fish">
                            <Setter Property="Content">
                                <Setter.Value>
                                    <Ellipse Fill="Red" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
                                </Setter.Value>
                            </Setter>
                        </DataTrigger>
                        <DataTrigger Binding="{Binding ElementName=MyComboBox, Path=SelectedItem.Content}" Value="Chips">
                            <Setter Property="Content">
                                <Setter.Value>
                                    <Ellipse Fill="Blue" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
                                </Setter.Value>
                            </Setter>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </ContentControl.Style>
        </ContentControl>
    </Grid>
</Grid>