开发者

[WPF]How to set width and height of a grid that is in a data template

开发者 https://www.devze.com 2022-12-17 03:37 出处:网络
Having the following wpf code: <Window x:Class=\"WpfApplication5.Window1\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"

Having the following wpf code:

<Window x:Class="WpfApplication5.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xam开发者_运维百科l"
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>

The output is this

[WPF]How to set width and height of a grid that is in a data template

I want that the state code to be displayed always in the right side of the listbox and this must happen also if I resize the window.

Any ideas ?


Ensure the HorizontalContentAlignment of each ListBoxItem is set to Stretch:

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


Make your Grid's HorizontalAlignment Stretch, not Left.

<DataTemplate x:Key="DataTemplate" DataType="{x:Type c:Place}">
    <Grid HorizontalAlignment="Stretch">
        <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>
0

精彩评论

暂无评论...
验证码 换一张
取 消