wpf - [WPF]如何设置数据模板中网格的宽度和高度

标签 wpf grid datatemplate

具有以下 wpf 代码:

<Window x:Class="WpfApplication5.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:WpfApplication5"
Title="Window1" Height="300" Width="300">
<Window.Resources>
    <c:Places x:Key="PlacesData"/>
    <DataTemplate x:Key="DataTemplate" DataType="{x:Type c:Place}">
        <Grid HorizontalAlignment="Left" 
              >
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="40"/>
            </Grid.ColumnDefinitions>
            <TextBlock Grid.Column="0" Text="{Binding Name}"/>
            <TextBlock Grid.Column="1" Text="{Binding State}" TextAlignment="Right"/>
        </Grid>
    </DataTemplate>
</Window.Resources>
<Grid>
    <ListBox ItemsSource="{Binding Source={StaticResource PlacesData}}" 
             ItemTemplate="{StaticResource DataTemplate}"
             ScrollViewer.HorizontalScrollBarVisibility="Disabled"  
             ScrollViewer.CanContentScroll="False"
             HorizontalContentAlignment="Stretch"/>
</Grid>

输出是这样的 alt text

我希望状态代码始终显示在列表框的右侧,并且如果我调整窗口大小,也必须发生这种情况。

有什么想法吗?

最佳答案

确保每个 ListBoxItemHorizo​​ntalContentAlignment 设置为 Stretch:

<ListBox>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

关于wpf - [WPF]如何设置数据模板中网格的宽度和高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2081908/

相关文章:

wpf - 使用 ControlTemplate 时 ListView 忽略 DataTemplates

WPF ContentControl 不显示任何内容

c# - 使用 wpf 浏览器取消导航

c# - 使用 Viewbox 缩放包含标签和文本框的网格

javascript - 具有定义列数的 Reactjs 网格布局

css - 将连续缩略图列表 Bootstrap 到网格中

c# - 在 DataTemplate 中排列 ItemsControl 项

wpf - 将 ListView 自动滚动到最后添加的项目的最佳方式是什么?

C# WPF XAML 在 UserControl 加载上运行 XAML 命令

c# - 从 WPF 数据网格中删除行