Concatenate strings instead of using a stack of TextBlocks

后端 未结 4 1069
北荒
北荒 2020-12-04 09:43

I want to show a list of Customer objects in a WPF ItemsControl. I\'ve created a DataTemplate for this:

    

        
4条回答
  •  北海茫月
    2020-12-04 09:58

    You can also use a bindable run. Useful stuff, especially if one wants to add some text formatting (colors, fontweight etc.).

    
       
       
       
    
    

    Here's an original class:
    Here are some additional improvements.
    And that's all in one piece of code:

    public class BindableRun : Run
        {
            public static readonly DependencyProperty BoundTextProperty = DependencyProperty.Register("BoundText", typeof(string), typeof(BindableRun), new PropertyMetadata(new PropertyChangedCallback(BindableRun.onBoundTextChanged)));
    
            private static void onBoundTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
            {
                ((Run)d).Text = (string)e.NewValue;
            }
    
            public String BoundText
            {
                get { return (string)GetValue(BoundTextProperty); }
                set { SetValue(BoundTextProperty, value); }
            }
    
            public BindableRun()
                : base()
            {
                Binding b = new Binding("DataContext");
                b.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(FrameworkElement), 1);
                this.SetBinding(DataContextProperty, b);
            }
        }
    

提交回复
热议问题