DataGrid中的自定义Html TextBlock

时间:2012-03-13 00:46:54

标签: wpf datagrid controls

我想在(只读)DataGrid中显示一种富文本。它应该包括基本样式(粗体,斜体)和超链接,即网格单元格应该采取类似的方式:     

<a>Here</a> and <a>also here</a> you can find <b>stuff<b>
并将其渲染为好像是html。当然,数据来自数据库,所以一切都应该是可绑定的。

在尝试修补相应的模板或样式后,我放弃并尝试进行自定义控制。控制非常简单:

public class SmartTextBlock : TextBlock
{
    public static readonly DependencyProperty HtmlProperty = DependencyProperty.Register("Html", typeof(string), typeof(SmartTextBlock), new UIPropertyMetadata(null, new PropertyChangedCallback(OnHtmlChanged)));

    public string Html
    {
        get { return GetValue(HtmlProperty) as string; }
        set { SetValue(HtmlProperty, value); }
    }

    static void OnHtmlChanged(DependencyObject target, DependencyPropertyChangedEventArgs e) {
        SmartTextBlock control = target as SmartTextBlock;
        control.createParts(e.NewValue as string);
    }

    void createParts(string text) {
        Inlines.Clear();
        /* parse text and add some Inlines */
    }
}

进展顺利,控制效果很好。它被平滑地添加到网格中:

<DataGridTemplateColumn Width="*" Header="Line">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <controls:SmartTextBlock Html="{Binding Path=Html}" TextWrapping="Wrap" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

问题是当我尝试调整大小或滚动网格时。然后整个窗口开始闪烁,应用程序挂起!这不会每次都发生,但如果你尝试的时间足够长,它肯定会开始。

任何可能导致这种情况的想法,我忽略了哪个明显的错误?

1 个答案:

答案 0 :(得分:0)

我终于设法解决了问题。它似乎起源于DataGrid本身!!

DataGrid有HeadersVisibility="Column",当我设置RowHeaderWidth="0"时,问题就消失了。

Dunno,如果这是主要原因,但它肯定解决了它。