我有一个绑定到富文本框,为此我创建了一个帮助器。我绑定到单个类属性。以下是代码和示例:
这是我创建的助手:
public class RichTextBoxHelper
{
/// <summary>
/// Text Attached Dependency Property
/// </summary>
public static readonly DependencyProperty TextProperty =
DependencyProperty.RegisterAttached("Text", typeof(string), typeof(RichTextBoxHelper),
new FrameworkPropertyMetadata((string)null,
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault |
FrameworkPropertyMetadataOptions.Journal,
new PropertyChangedCallback(OnTextChanged),
new CoerceValueCallback(CoerceText),
true,
UpdateSourceTrigger.PropertyChanged));
/// <summary>
/// Gets the Text property.
/// </summary>
public static string GetText(DependencyObject d)
{
return (string)d.GetValue(TextProperty);
}
/// <summary>
/// Sets the Text property.
/// </summary>
public static void SetText(DependencyObject d, string value)
{
d.SetValue(TextProperty, value);
}
/// <summary>
/// Returns the Text from a FlowDocument
/// </summary>
/// <param name="document">The document to get the text from</param>
/// <returns>Returns a string with the text of the flow document</returns>
public static string GetText(FlowDocument document)
{
return new TextRange(document.ContentStart, document.ContentEnd).Text;
}
/// <summary>
/// Handles changes to the Text property.
/// </summary>
private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
RichTextBox textBox = (RichTextBox)d;
if (e.NewValue != null)
{
textBox.Document.Blocks.Clear();
textBox.Document.Blocks.Add(new Paragraph(new Run(e.NewValue.ToString())));
}
}
private static object CoerceText(DependencyObject d, object value)
{
return value ?? "";
}
XAML中的代码是:
<RichTextBox Name="txtView"
AcceptsReturn="False"
Grid.Column="2"
Grid.Row="5"
BorderThickness="0"
Margin="2,5,5,2"
HorizontalAlignment="Stretch"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Auto"
local:RichTextBoxHelper.Text="{Binding SelectedItem.ItemData.Description}">
我的View模型中的Selected项目是:
public DataDetail SelectedItem
{
get
{
return this.selectedItem;
}
set
{
this.selectedItem = value;
base.RaisePropertyChanged("SelectedItem");
}
}
DataDetail类的结构和嵌套属性如下:
public class DataDetail
{
public ItemData ItemData { get; set; }
// Other properies (other class objects
}
public class ItemData
{
public string Name { get; set; }
public string Description { get; set; }
// Other properties (string and int, float)
}
问题是Richbox中的数据是从这个属性中读取的,但当我尝试更改Richtextbox中的任何内容时(在UI中),它不会进入该属性。当我将Name属性绑定到文本框并且通过在XAML中指定它时可以工作(读取和更新)
<TextBox Text="{Binding SelectedItem.ItemData.Name}"></TextBox>
Richtext框中有什么问题?
感谢任何帮助。
答案 0 :(得分:-2)
属性如何知道它发生了变化?没有描述它应该与RichTextBox中段落的内容相对应。您需要观察RichTextBox内容及其Text属性的所有更改,并手动change the current value查看附加的Text属性。