Sentropie
Sentropie

Reputation: 259

TextBox in UserControl doesn't take all the space

I have a WPF listbox with custom items. Each item is a user control consisting of a grid with two textboxes. I want that the right one takes all the space to fill the ListBoxItem. But all I get working is that the item itself takes the whole space but the textbox takes the size of its content.

So this is the listbox:

    <ListBox x:Name="leftListBox" Grid.Column="0" Margin="10" 
             HorizontalContentAlignment="Stretch">
        <ListBox.ItemTemplate>
            <DataTemplate>                    
                    <local:CustomLine />                    
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

And the user control:

<UserControl x:Class="SharpComparer.CustomLine"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="30">
    <UserControl.Resources>
        <Style TargetType="{x:Type TextBox}">
             <Setter Property="VerticalAlignment" Value="Center" />
        </Style>
    </UserControl.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="40" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <TextBox x:Name="NumberColumn" x:FieldModifier="public" 
                 Text="{Binding LineNumber}"
                 Grid.Column="0" HorizontalAlignment="Right" />
        <TextBox x:Name="TextColumn" x:FieldModifier="public" 
                 Text="{Binding Text}"
                 Grid.Column="1" HorizontalAlignment="Left" />
    </Grid>
</UserControl>

What I have already tried after some research at some MSDN posts and around here on Stack Overflow: Setting the HorizontalContentAlignment to Stretch for Listbox.ItemContainerStyle. I used some borders to find the piece which makes problems. The ListBoxItems seem to take the whole width, the usercontrol and its grid, too. The textbox does not take all the space although I thought that Width="*" inside the grid's ColumnDefinition would do that.
Another idea was to bind the textbox width to its parent size, but then it also takes the space of the left textbox (which makes sense, because it gets the whole width) and subtracting this width doesn't seem to work.

What am I doing wrong?

Upvotes: 1

Views: 1320

Answers (1)

Maurizio Reginelli
Maurizio Reginelli

Reputation: 3222

You have to change your UserControl code from this:

<TextBox x:Name="TextColumn" x:FieldModifier="public" 
                 Text="{Binding Text}"
                 Grid.Column="1" HorizontalAlignment="Left" />

to this:

<TextBox x:Name="TextColumn" x:FieldModifier="public" 
                 Text="{Binding Text}"
                 Grid.Column="1" HorizontalAlignment="Stretch" />

Upvotes: 2

Related Questions