在XAML中的ItemsControl中拉伸项目

Flo*_*ser 2 xaml windows-phone-8.1

能够达到预期效果的最短代码对我来说:

<ItemsControl ItemsSource="{Binding GeneralBoolSettings}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Grid>
                <ToggleSwitch IsOn="{Binding IsOn, Mode=TwoWay}" OffContent="{Binding OffContent}" OnContent="{Binding OnContent}" />
            </Grid>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
    <ItemsControl.ItemContainerStyle>
        <Style TargetType="ContentPresenter">
            <Setter Property="HorizontalAlignment" Value="Stretch"/>
        </Style>
    </ItemsControl.ItemContainerStyle>
</ItemsControl>
Run Code Online (Sandbox Code Playgroud)

原始问题

我遇到的问题就像拉伸ItemControl水平物品一样简单.当我在使用XAML时,我没有像SharedSizeGroupWPF那样的东西.

这里介绍的解决方案:不幸的是,ItemsControl中的水平拉伸内容对我不起作用.我的代码:

<ItemsControl ItemsSource="{Binding GeneralBoolSettings}" HorizontalContentAlignment="Stretch">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Grid>
                <ToggleSwitch IsOn="{Binding IsOn, Mode=TwoWay}" OffContent="{Binding OffContent}" OnContent="{Binding OnContent}" />
            </Grid>
        </DataTemplate>
        </ItemsControl.ItemTemplate>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Vertical" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>
Run Code Online (Sandbox Code Playgroud)

Designer的一些截图:

ItemControl具有正确的(拉伸)大小 ItemControl具有正确的大小

DataTemplate已经太小了 在此输入图像描述

我想避免绑定到父宽度; 在我以前的尝试中,宽度有时(重新)设置为0,我将不得不删除绑定并再次添加它.另外:请不要使用代码和/或事件捕手,必须有一个优雅的解决方案来解决这个相当基本的问题!

老实说,我有点惊讶我不能让这个工作.Mabye你可以推荐一本好书/网站来学习XAML基础知识的系统方法(当我们在这里时)?

Ahm*_*med 5

您还需要使用ItemsControl的ItemContainerStyle属性设置每个项容器的水平对齐方式以进行拉伸.

<ItemsControl ItemsSource="{Binding GeneralBoolSettings}" HorizontalContentAlignment="Stretch">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <ToggleSwitch IsOn="{Binding IsOn, Mode=TwoWay}" OffContent="{Binding OffContent}" OnContent="{Binding OnContent}" />
                </Grid>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Vertical" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemContainerStyle>
            <Style TargetType="ContentPresenter">
                <Setter Property="HorizontalAlignment" Value="Stretch"/>
            </Style>
        </ItemsControl.ItemContainerStyle>
    </ItemsControl>
Run Code Online (Sandbox Code Playgroud)