C# 绑定到RichTextBox块属性
我想直接绑定到Xaml中的C# 绑定到RichTextBox块属性,c#,.net,xaml,windows-phone-8,C#,.net,Xaml,Windows Phone 8,我想直接绑定到Xaml中的RichTextBox的Blocks属性。这是不可能的,因为块属性是只读的。我可以直接绑定到单个跑步: <RichTextBox x:Name="MyRichTextBox" FontSize="36" Margin="10" Foreground="White"> <Paragraph> <Run Text="{Binding MyObject.Text}" Foreground="Yellow"/>
RichTextBox
的Blocks属性。这是不可能的,因为块
属性是只读的。我可以直接绑定到单个跑步:
<RichTextBox x:Name="MyRichTextBox" FontSize="36" Margin="10" Foreground="White">
<Paragraph>
<Run Text="{Binding MyObject.Text}" Foreground="Yellow"/>
<Run Text="{Binding MyObject.Text}" Foreground="Cyan"/>
</Paragraph>
</RichTextBox>
我想做一些类似的事情:
<RichTextBox x:Name="MyRichTextBox" Blocks="{Binding MyObject.RichTextBlocks}" FontSize="36" Margin="10" Foreground="White"/>
特别是因为我事先不知道绑定对象将返回多少块
实现这一点的正确方法是使用RichTextBlocks
属性为RichTextBox
创建附加行为,该属性在设置时通过块枚举并为每个块调用RichTextBox.blocks.Add()
我不熟悉C#、.NET和XAML,因此请原谅这个基本问题,如果能给出一个简单解释的答案,我将不胜感激。通过@Nogard和另一篇文章中的指针,我创建了自己的类,它具有一个名为
RichText
的依赖属性。在这里张贴,以防对其他人有用
public class MyRichTextBox : RichTextBox
{
public static readonly DependencyProperty RichTextProperty = DependencyProperty.Register("RichText", typeof(Paragraph), typeof(MyRichTextBox), new PropertyMetadata(null, RichTextPropertyChanged));
public Paragraph RichText
{
get
{
return (Paragraph)GetValue(RichTextProperty);
}
set
{
SetValue(RichTextProperty, value);
}
}
private static void RichTextPropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
MyRichTextBox richTextBox = (MyRichTextBox)dependencyObject;
Paragraph paragraph = (Paragraph)dependencyPropertyChangedEventArgs.NewValue;
// Remove any existing content from the text box
richTextBox.Blocks.Clear();
// Add the paragraph to the text box
richTextBox.Blocks.Add(paragraph);
}
}
}
并将此添加到我的xaml
<sub:MyRichTextBox x:Name="MyRichTextOverlay" RichText="{Binding CurrentOverlay.RichTextParagraph}" VerticalAlignment="Top" FontSize="36" Margin="10" Foreground="White" HorizontalAlignment="Center" TextWrapping="Wrap" TextAlignment="Center"/>
OOTB解决方案不适用于此-因此,WP7的任何解决方案都可以使用。检查以下答案: