Hi I try to create an Attached Property so that i'm able to bind my FlowDocument
to an RichTextBox
Here my Code
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);
}
};
}
}
}
here the 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.
and here the Error:
{"\"Binding\" kann nicht für die Eigenschaft \"SetDocument\" vom Typ \"RichTextBox\" festgelegt werden. \"Binding\" kann nur für eine \"DependencyProperty\" eines \"DependencyObject\" festgelegt werden."}
i know what this error means but i don't know how to solve this because don't know what DependencyObject i need ...
it would be nice if somebody could point out which object he expect
The names of the static getter and setter methods for an attached property
X
have to beGetX
andSetX
. So if you have an attached propertyAttachFlowDocument
they have to look like this: