您好我尝试创建一个附加属性,以便我能够将FlowDocument
绑定到RichTextBox
这是我的代码
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
namespace Speiseplandienst.Tools
{
public static class RichTextBoxHelper
{
public static FlowDocument GetDocument(DependencyObject obj)
{
return (FlowDocument)obj.GetValue(AttachFlowDocumentProperty);
}
public static void SetDocument(DependencyObject obj, FlowDocument value)
{
obj.SetValue(AttachFlowDocumentProperty, value);
}
public static readonly DependencyProperty AttachFlowDocumentProperty =
DependencyProperty.RegisterAttached(
"AttachFlowDocument",
typeof(FlowDocument),
typeof(RichTextBoxHelper),
new FrameworkPropertyMetadata(
default(FlowDocument),
FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
OnPropertyChangedCallBack));
private static void OnPropertyChangedCallBack(
DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var richTextBox = (RichTextBox)obj;
// Parse the XAML to a document (or use XamlReader.Parse())
try
{
// Set the document
richTextBox.Document = GetDocument(richTextBox);
}
catch (Exception)
{
richTextBox.Document = new FlowDocument();
}
// When the document changes update the source
richTextBox.TextChanged += (obj2, e2) =>
{
RichTextBox richTextBox2 = obj2 as RichTextBox;
if (richTextBox2 != null)
{
SetDocument(obj, richTextBox2.Document);
}
};
}
}
}
这里是Stacktrace:
bei System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
bei System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
bei System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
bei System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
bei Speiseplandienst.Views.MenuItemV.InitializeComponent() in c:\Users\MReimann\Desktop\...\...\...\...\MenuItemV.xaml:Zeile 1.
bei Speiseplandienst.Views.MenuItemV..ctor() in c:\Users\MReimann\Desktop\...\...\...\...\MenuItemV.xaml.cs:Zeile 24.
这里是错误:
{"\"Binding\" kann nicht für die Eigenschaft \"SetDocument\" vom Typ \"RichTextBox\" festgelegt werden. \"Binding\" kann nur für eine \"DependencyProperty\" eines \"DependencyObject\" festgelegt werden."}
我知道这个错误意味着什么,但我不知道如何解决这个问题因为不知道我需要什么DependencyObject ...
如果有人可以指出他期望的对象,那就太好了答案 0 :(得分:1)
附加属性X
的静态getter和setter方法的名称必须为GetX
和SetX
。因此,如果您有附加属性AttachFlowDocument
,则必须如下所示:
public static FlowDocument GetAttachFlowDocument(DependencyObject obj)
{
return (FlowDocument)obj.GetValue(AttachFlowDocumentProperty);
}
public static void SetAttachFlowDocumentDocument(
DependencyObject obj, FlowDocument value)
{
obj.SetValue(AttachFlowDocumentProperty, value);
}