首页 > 解决方案 > 使用 ItemTemplating 更改网格的内容

问题描述

现在的情况

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

 <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>

我的任务

我的控件数量超出了我的窗口所能容纳的数量。我想让用户在所有可用的控件之间进行切换,方法是在 中选择他喜欢的控件,ComboBox然后按Button.

我考虑过使用 ItemTemplating 来实现这一点。我发现这篇文章是关于如何处理不同类型的 DataTypes,这很有帮助。然而我觉得这里的列表有点多余,因为它总是只有一个项目,但我不知道该用什么来代替。

我的问题

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

标签: c#wpfxamlitemtemplate

解决方案


此处的代码将实现一个控件,其内容根据组合框的值而变化。这只是使用省略号,但如果需要,您可以将自己的用户控件插入 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>

推荐阅读