问题
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