Search code examples
wpfrichtextboxdatatemplate

RichTextBox in DataTemplate not filling


I have a RichTextBox in a DataTemplate and it is not filling the space while other controls are. It is as if the RichTextBox is set to a Width="1" Here is my DataTemplate;

<DataTemplate x:Key="MyDataTemplate" >
   <StackPanel>
       <RichTextBox />
       <TextBox />
   </StackPanel>
</DataTemplate >

This is what it looks like if I type "12345" with no spaces or returns; enter image description here

Also here is how I use the DataTemplate ;

<ListBox  Margin="2" SelectionMode="Single" ItemTemplate="{StaticResource MyDataTemplate}"/>

Note: If I sent the RichTextBox MinWidth to something it does make it better (for example "12345" would appear correctly), but still does not fill the space.


Solution

  • The template:

        <DataTemplate x:Key="MyDataTemplate" >
            <StackPanel x:Name="Panel">
                <RichTextBox Width="{Binding ElementName=Panel, Path=ActualWidth}" />
                <TextBox />
            </StackPanel>
        </DataTemplate >
    

    And your list:

    <ListBox ItemTemplate="{StaticResource MyDataTemplate}"
             HorizontalContentAlignment="Stretch"
             ItemsSource="{Binding }"/>