简体   繁体   中英

When to render custom WPF TextBlock?

When should I be building Inlines in a TextBlock? I have a TextBlock-derived class that, when given text in a certain field, call it MyText, converts the text into a set of inlines when MyText has changed.

Whenever MyText changes, I clear the Inlines and build them, colorizing each word as needed. For this example, consider:

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);
    }
}

This has worked very well. However, recently we placed the Control into a DataGrid, and some strange things have started happening. Apparently the DataGrid swaps out the context and for the most part this works. However, when we add or delete data from the DataGrid ItemsSource, something goes awry, and TextChanged doesn't seem like it is called (or at least not called at the same time). MyText can be one value, and the Inlines either blank or a different value.

I think that the place to build the Inlines is NOT during MyTextChanged, but maybe when the rendering of the Control starts. I've also tried when the DataContextChanged, but this does not help.

In my constructor, I have

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

corresponding to a dependency property I have in the class

    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;

Update: If it is any kind of clue, the problem DataGrid cells seem to be the ones that are off-screen when the addition or removal happens. I also tried OnApplyTemplate, but that didn't help.

Update2: Perhaps a better solution might be to create bindable inlines?

DataGrids virtualize their content, so if a row is not visible it will not be loaded. That being the case, have you tried also rebuilding the inlines when the Loaded event fires?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM