2

So I have a ListBox that has a DataTemplate which has a Grid which has a RichTextBox. For some reason when you type into the RichTextBox it puts each character on a separate line. Digging into this, I find out that the ExtentWidth is equal to 10.003. Why? I have no idea. I was hoping someone could explain to me why and give a nice solution to make it stop doing this.

I did notice that if you set a width on the grid's column, it fixes it, but I don't want a static width on my grid's column.

Below is an example of the problem. I am using .Net 4 and VS 2010.

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1"
    Title="MainWindow" Height="350" Width="525">
<ListBox 
    DockPanel.Dock="Top" 
    x:Name="TestListBox">
    <ListBox.ItemTemplate>
        <DataTemplate DataType="{x:Type local:Test}">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="50" />
                    <ColumnDefinition />
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <TextBox Grid.Column="0" Grid.Row="0" Text="{Binding Name}" />
                <TextBlock Grid.Column="1" Grid.Row="0" Text="Test" />
                <RichTextBox
                    Grid.Column="1" Grid.Row="1"/>
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
    <local:Test Name="Test1" />
    <local:Test Name="Test2" />
</ListBox>

using System.Windows;

namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
}

public class Test
{
    public string Name { get; set; }

    public Test()
    {
    }
}
}
4

1 に答える 1

0

So I figured out a workaround. If you trade out the ListBox for a DataGrid and use DataGridTemplateColumns with the Width of the TemplateColumn set to "*" then it seems to work.

<DataGrid
    x:Name="TestDataGrid"
    CanUserReorderColumns="False"
    CanUserResizeColumns="False"
    >
    <DataGrid.Columns >
        <DataGridTemplateColumn Width="*">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <RichTextBox />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>

    <local:Test Name="Test1" />
    <local:Test Name="Test2" />
</DataGrid>

Note I also set the CanUserResizeColumns to False because if you don't and they resize them, the ExtentWidth will snap back to 10.

于 2012-09-10T18:37:20.633 に答える