Sl 4, MVVM: Using Inlines in a TextBlock, how to bind to the ViewModel?

主宰稳场 提交于 2020-01-05 03:07:29

问题



We format text for a TextBlock by adding a series of System.Windows.Documents.Run objects to TextBlock.Inlines.

How can we bind the formatted text in the ViewModel to display in the TextBlock?

Thanks for any advice...


回答1:


I attempted creating an InlineCollection property in aViewModel, then set the binding in the xaml, but the InlineCollection in TextBlock is not bindable, since it is not a DependencyProperty. The answer to this question shows creating your own control and making it a DependencyProperty which is an ok workaround.

VM:

private InlineCollection inlineCollection;

 public InlineCollection TextBlockInlineCollection {
    get
    {
        return inlineCollection;
    }
    set
    {
        inlineCollection = value;
        NotifyPropertyChanged("TextBlockInlineCollection");
    }
}

xaml: // doesn't work

You could also create the TextBlock dynamically in code using the XamlReader: example:

   string textBlock = @"<TextBlock xmlns='http://schemas.microsoft.com/client/2007' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' x:Name='infoBarTextBlockWithFormatting' AutomationProperties.AutomationId='infoBarTextBlockWithFormatting' Margin='9,0,0,0' TextWrapping='Wrap'>";
   textBlock = String.Concat(textBlock, e.NewValue.ToString(), "</TextBlock>");
   infoBar.infoBarRunHolder.Child = (TextBlock)XamlReader.Load(textBlock);


来源:https://stackoverflow.com/questions/5473002/sl-4-mvvm-using-inlines-in-a-textblock-how-to-bind-to-the-viewmodel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!