解决方案
实现所需结果的最短代码对我来说是:
<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>
原始问题
我在处理像水平拉伸(stretch) ItemControl
的项目这样简单的事情时遇到了麻烦。当我使用 XAML 时,我没有 WPF 中的 SharedSizeGroup
之类的东西。
此处提供的解决方案:Horizontally Stretch Content in an 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>
设计师的一些截图:
ItemControl 具有正确的(拉伸(stretch))尺寸
DataTemplate 已经太小了
我想避免绑定(bind)到父宽度;在我之前的尝试中,宽度有时(重新)设置为 0,我必须删除绑定(bind)并再次添加它。另外:请不要使用代码和/或事件捕获器,必须有一个优雅的解决方案来解决这个相当基本的问题!
老实说,我有点惊讶我无法让它发挥作用。也许您可以推荐一本好书/网站来学习 XAML 基础知识的系统方法(当我们这样做时)?
最佳答案
您还需要使用 ItemsControl 的 ItemContainerStyle 属性将每个项目容器的水平对齐方式设置为拉伸(stretch)。
<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>
关于xaml - 在 XAML 中拉伸(stretch) ItemsControl 中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30274333/