Dolev Goaz
Dolev Goaz

Reputation: 41

get access to the window size xaml DataTemplate WPF

So, i have the following xaml at the moment-

<Window.Resources>
    <DataTemplate x:Key="MailTemplate">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding Path=Date}" Width="150"/>
            <TextBlock Text="{Binding Path=Subject}" Width="300"/>
            <TextBlock Text="{Binding Path=From.DisplayName}" Width="125"/>
        </StackPanel>
    </DataTemplate>
</Window.Resources>

It's a template of a ListBox item. The actual details do not really matter, its just about the Width attribute. Is there a way to access the window's size in order to set the width? I don't want the Width to be constant, i want the TextBlocks to be able to change sizes if you stretch the window.

Upvotes: 0

Views: 134

Answers (1)

bassfader
bassfader

Reputation: 1356

You can do that by not setting any fixed widths on the TextBlock elements, and use a Grid with star-sizing instead of a StackPanel as container. For example like this:

<DataTemplate x:Key="MailTemplate">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="150*" />
            <ColumnDefinition Width="300*" />
            <ColumnDefinition Width="125*" />
        </Grid.ColumnDefinitions>

        <TextBlock Grid.Column="0" Text="{Binding Path=Date}" />
        <TextBlock Grid.Column="1" Text="{Binding Path=Subject}" />
        <TextBlock Grid.Column="2" Text="{Binding Path=From.DisplayName}" />
    </Grid>
</DataTemplate>

Upvotes: 1

Related Questions