我的 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/