ryan0270
ryan0270

Reputation: 1145

WPF RichTextBox inside DataGrid format is messed up

I need to use RichTextBoxes in a column of a DataGrid. This is done in xaml via

<DataGrid x:Name="ui_tblInputs"
                Grid.Row="0" Grid.Column="2" Grid.RowSpan="3"
                AutoGenerateColumns="False"
                HeadersVisibility="Column"
                CanUserSortColumns="False"
                HorizontalAlignment="Center"
                ItemsSource="{Binding InputPorts, Mode=OneWay}"
                SelectedItem="{Binding SelectedInputPort}"
                SelectionMode="Single"
                >
    <DataGrid.Columns>
        <DataGridTextColumn
                        Header="Inputs"
                        Width="SizeToCells"
                        MinWidth="50"
                        Binding="{Binding Name, Mode=TwoWay}"
                        />
        <DataGridTemplateColumn
                        Header="Test Value"
                        Width="SizeToCells"
                        MinWidth="100"
                        >
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <RichTextBox
                                    IsReadOnly="True"
                                    >
                        <FlowDocument>
                            <Paragraph>
                                <Run Text="some text"/>
                            </Paragraph>
                        </FlowDocument>
                    </RichTextBox>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

Problem is, the text inside the RichTextBox is coming out with each character on it's own line. i.e.

image output

Any thoughts as to why this is happening?

Upvotes: 2

Views: 3110

Answers (1)

Norman Skinner
Norman Skinner

Reputation: 6985

You could give the DataGridTemplateColumn a name like: x:Name="ThisColumn" And then in the RichTextBox set the width like this:

Width="{Binding ElementName=ThisColumn, Path=ActualWidth}"

UPDATE: Ok the problem is a bug here is a work around. Set the "FlowDocument" width to the RichTextBox width which takes the width of the cell.

<DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
        <RichTextBox 
            x:Name="My_RTB"
            IsReadOnly="True">
            <FlowDocument
                PageWidth="{Binding ElementName=My_RTB, Path=ActualWidth}">
                <Paragraph>
                    <Run Text="some text"/>
                </Paragraph>
            </FlowDocument>
        </RichTextBox>
    </DataTemplate>
</DataGridTemplateColumn.CellTemplate>

Upvotes: 4

Related Questions