TextBox in UserControl doesn't take all the space

匆匆过客 提交于 2019-12-11 04:18:23

问题


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?


回答1:


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" />


来源:https://stackoverflow.com/questions/9045225/textbox-in-usercontrol-doesnt-take-all-the-space

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!