WPF data template width

I have data template formatting elements in a ListBox

<DataTemplate x:Key="ChildViewModelTemplate">
    <Border BorderBrush="#FFDC1C1C" BorderThickness="1" >
        <Grid>
            <TextBlock Text="{Binding Path=DisplayName}"></TextBlock>
            <Image Height="Auto" Margin="0,0,2,0" VerticalAlignment="Stretch" HorizontalAlignment="Right" Width="31" Source="pack://siteoforigin:,,,/rocket.ico"/>
        </Grid>
    </Border>                
</DataTemplate>

This places a border around each element that extends to the length of the text string associated with the TextBlock binding.

Is there an easy way to have all elements of the same width where the width is equal to the longest element? For bonus points, I wonder if there is a way to do this for the longest visible element and / or the longest element, regardless of whether it is visible.

thank

+3
source share
2 answers

Botz3000. SharedSizeGroup - .

<ListBox ...
         Grid.IsSharedSizeScope="True">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto" SharedSizeGroup="Col1"/>
                </Grid.ColumnDefinitions>
                <Border BorderBrush="#FFDC1C1C" BorderThickness="1" >
                    <Grid>
                        <TextBlock Text="{Binding Path=DisplayName}"></TextBlock>
                        <Image Height="Auto" Margin="0,0,2,0" VerticalAlignment="Stretch" HorizontalAlignment="Right" Width="31" Source="C:\C1.png"/>
                    </Grid>
                </Border>
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
+3

Source: https://habr.com/ru/post/1778943/


All Articles