wpf - 数据绑定(bind) TextBlock.Inlines

标签 wpf data-binding textblock inlines

我的 WPF 应用程序从需要在 UI 中显示的后端服务接收消息流。这些消息差异很大,我希望每条消息都有不同的视觉布局(字符串格式、颜色、字体、图标等)。

我希望能够为每条消息创建一个内联(运行、文本 block 、斜体等),然后以某种方式将它们全部放入 ObservableCollection<>并在 UI 中的 TextBlock.Inlines 上使用 WPF 数据绑定(bind)的魔力。我找不到如何做到这一点,这可能吗?

最佳答案

这是利用 WPF 行为/附加属性的替代解决方案:

public static class TextBlockExtensions
{
    public static IEnumerable<Inline> GetBindableInlines ( DependencyObject obj )
    {
        return (IEnumerable<Inline>) obj.GetValue ( BindableInlinesProperty );
    }

    public static void SetBindableInlines ( DependencyObject obj, IEnumerable<Inline> value )
    {
        obj.SetValue ( BindableInlinesProperty, value );
    }

    public static readonly DependencyProperty BindableInlinesProperty =
        DependencyProperty.RegisterAttached ( "BindableInlines", typeof ( IEnumerable<Inline> ), typeof ( TextBlockExtensions ), new PropertyMetadata ( null, OnBindableInlinesChanged ) );

    private static void OnBindableInlinesChanged ( DependencyObject d, DependencyPropertyChangedEventArgs e )
    {
        var Target = d as TextBlock;

        if ( Target != null )
        {
            Target.Inlines.Clear ();
            Target.Inlines.AddRange ( (System.Collections.IEnumerable) e.NewValue );
        }
    }
}
在您的 XAML 中,像这样使用它:
<TextBlock MyBehaviors:TextBlockExtensions.BindableInlines="{Binding Foo}" />
这使您不必从 TextBlock 继承。它也可以使用 可观察集合 而不是 IEnumerable ,在这种情况下,您需要订阅集合更改。

关于wpf - 数据绑定(bind) TextBlock.Inlines,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1959856/

相关文章:

wpf - 如何在 XAML 中绘制一个 'felt pen' 样式的圆而不结束连接

.net - WPF 中缺少的功能

c# - wpf中的UserControl显示顺序

javascript - AngularJS : ng-bind-html depending on variable

wpf - 无法在 WPF 中编辑 Textblock 内容

.net - 实现自己的 MVVM 还是使用 MVVM 框架?

javascript - 如何轻松确定 $scope.$watch 中添加/删除的内容?

WPF MVVM Light - SelectedItem 的绑定(bind)没有改变

wpf - 标签和文本 block 之间的区别

c# - 以编程方式在文本之间制作带有超链接的文本 block