【问题标题】:When to render custom WPF TextBlock?何时呈现自定义 WPF TextBlock?
【发布时间】:2011-06-04 23:42:46
【问题描述】:

我应该什么时候在 TextBlock 中构建内联?我有一个 TextBlock 派生类,当在某个字段中给定文本时,将其称为 MyText,当 MyText 发生更改时,将文本转换为一组内联。

每当 MyText 发生变化时,我都会清除内联并构建它们,并根据需要为每个单词着色。对于此示例,请考虑:

private void MyTextBlock_MyTextChanged(object sender, EventArgs e)
{
    Inlines.Clear();
    if (!string.IsNullOrEmpty(this.MyText))
    {
        var run = new Run();
        run.Foreground = Brushes.DarkRed;
        run.Text = this.MyText;
        Inlines.Add(run);
    }
}

这非常有效。然而,最近我们将控件放入一个DataGrid,并且开始发生一些奇怪的事情。显然,DataGrid 交换了上下文,并且在大多数情况下这是有效的。但是,当我们从 DataGrid ItemsSource 添加或删除数据时,出现了问题,并且 TextChanged 似乎没有被调用(或者至少没有同时被调用)。 MyText 可以是一个值,而 Inlines 可以是空白或不同的值。

我认为构建内联的地方不是在 MyTextChanged 期间,而是可能在控件的渲染开始时。当DataContextChanged我也试过了,但这并没有帮助。

在我的构造函数中,我有

   this.myTextDescriptor = DependencyPropertyDescriptor.FromProperty(
        MyTextProperty, typeof(MyTextBlock));
    if (this.myTextDescriptor != null)
    {
        this.myTextDescriptor.AddValueChanged(this, this.MyTextBlock_MyTextChanged);
    }

对应于我在类中的一个依赖属性

    public string MyText
    {
        get { return (string)GetValue(MyTextProperty); }
        set { SetValue(MyTextProperty, value); }
    }

    public static readonly DependencyProperty MyTextProperty =
        DependencyProperty.Register("MyText", typeof(string), typeof(MyTextBlock));

    private readonly DependencyPropertyDescriptor myTextDescriptor;

更新:如果有任何线索,问题 DataGrid 单元格似乎是在添加或删除发生时不在屏幕上的单元格。我也尝试过 OnApplyTemplate,但没有帮助。

Update2:也许更好的解决方案是创建可绑定的内联?

【问题讨论】:

    标签: c# wpf rendering textblock


    【解决方案1】:

    DataGrids 虚拟化它们的内容,因此如果一行不可见,它将不会被加载。既然如此,您是否尝试过在Loaded 事件触发时重建内联?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-18
      • 1970-01-01
      • 2011-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多