This project has moved. For the latest updates, please go here.

Richtextbox {Binding Notes}

Mar 10, 2011 at 7:04 PM

Hello,

I've been trying to figure out what I need to do to get the Text property to work properly. I sadly cannot understand what the documentation tells me to do with the Notes property, I especially miss how "the value of the notes property in rtf format" is used.

The value I'm talking about is this one: {\rtf1\ansi\ansicpg1252\uc1\htmautsp\deff2{\fonttbl{\f0\fcharset0 Times New Roman;}{\f2\fcharset0 Segoe UI;}}{\colortbl\red0\green0\blue0;\red255\green255\blue255;}\loch\hich\dbch\pard\plain\ltrpar\itap0{\lang1033\fs18\f2\cf0 \cf0\ql{\f2 {\ltrch This is the }{\b\ltrch RichTextBox}\li0\ri0\sa0\sb0\fi0\ql\par}}}

I googled for quite some time, and I was unable to find any code samples. Could someone post a small piece of code showing me how the Notes property is supposed to look like?

Somewhere in these discussions I found this:

 

private string _Notes;
public string Notes
{
    get { return _Notes; }
    set
    {
       _Notes = value;
       //OnPropertyChanged("Notes"); <---- The "Notes" string is seen as an invalid argument
  }
}

This is the furthest I got. Help is very much appreciated.

 

Mar 10, 2011 at 7:18 PM

The class that contains the Notes property should implement the INotifyPropertyChanged interface.  This is where the OnPropertyChanged("Notes") comes into play.  The INotifyPropertyChanged interface if responsible for notifying the UI when the value for a property has been updated.

Mar 10, 2011 at 7:55 PM

Thank you for helping me, I got quite a bit further now, but the "Notes property value" is still something I don't totally get.

public event PropertyChangedEventHandler PropertyChanged;

        private string _Notes = @"{\rtf1\ansi\ansicpg1252\uc1\htmautsp\deff2{\fonttbl{\f0\fcharset0 Times New Roman;}{\f2\fcharset0 Segoe UI;}}{\colortbl\red0\green0\blue0;\red255\green255\blue255;}\loch\hich\dbch\pard\plain\ltrpar\itap0{\lang1033\fs18\f2\cf0 \cf0\ql{\f2 {\ltrch This is the }{\b\ltrch RichTextBox}\li0\ri0\sa0\sb0\fi0\ql\par}}}";
        public string Notes
        {
            get { return _Notes; }
            set
            {
                _Notes = value;
                OnPropertyChanged("Notes");
            }
        }

        // Create the OnPropertyChanged method to raise the event
        protected void OnPropertyChanged(string _text)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(_text));
            }
        }

When I just enter "private string _Notes;" and when I use the long property value, I get the same error:

Unrecognized structure in data format 'Rich Text Format'.
Parameter name: stream

What is it I am doing wrong?

Mar 10, 2011 at 8:03 PM

just set _Notes = String.Empty;

Mar 10, 2011 at 8:34 PM

I have done that, and still get the same error. From testing I know that the problem lies in the code I posted earlier, without it the crash doesn't occur.

The whole error message, don't know if it is of much use:

System.ArgumentException was unhandled
  Message=Unrecognized structure in data format 'Rich Text Format'.
Parameter name: stream
  Source=PresentationFramework
  ParamName=stream
  StackTrace:
       at System.Windows.Documents.TextRangeBase.Load(TextRange thisRange, Stream stream, String dataFormat)
       at System.Windows.Documents.TextRange.LoadVirtual(Stream stream, String dataFormat)
       at System.Windows.Documents.TextRange.Load(Stream stream, String dataFormat)
       at Microsoft.Windows.Controls.RtfFormatter.SetText(FlowDocument document, String text)
       at Microsoft.Windows.Controls.RichTextBox.OnTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
       at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
       at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
       at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
       at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)
       at System.Windows.DependencyObject.InvalidateProperty(DependencyProperty dp)
       at System.Windows.Data.BindingExpressionBase.Invalidate(Boolean isASubPropertyChange)
       at System.Windows.Data.BindingExpression.TransferValue(Object newValue, Boolean isASubPropertyChange)
       at System.Windows.Data.BindingExpression.Activate(Object item)
       at System.Windows.Data.BindingExpression.AttachToContext(AttachAttempt attempt)
       at System.Windows.Data.BindingExpression.MS.Internal.Data.IDataBindEngineClient.AttachToContext(Boolean lastChance)
       at MS.Internal.Data.DataBindEngine.Task.Run(Boolean lastChance)
       at MS.Internal.Data.DataBindEngine.Run(Object arg)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
       at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
       at System.Windows.Threading.DispatcherOperation.InvokeImpl()
       at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
       at System.Threading.ExecutionContext.runTryCode(Object userData)
       at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Windows.Threading.DispatcherOperation.Invoke()
       at System.Windows.Threading.Dispatcher.ProcessQueue()
       at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
       at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
       at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
       at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
       at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
       at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
       at System.Windows.Threading.Dispatcher.Run()
       at System.Windows.Application.RunDispatcher(Object ignore)
       at System.Windows.Application.RunInternal(Window window)
       at System.Windows.Application.Run(Window window)
       at System.Windows.Application.Run()
       at RichTextBoxProject.App.Main() in C:\Users\MangoTree\documents\visual studio 2010\Projects\RichTextBoxProject\RichTextBoxProject\obj\x86\Debug\App.g.cs:line 0
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:

Is there really nothing wrong with my earlier piece of code?

This is my xaml piece for the richtextbox:

<extToolkit:RichTextBox Text="{Binding Notes}" Name="rTextBoxQuestion" Margin="0,15,0,0" MinWidth="150" />

And before that I tried this:
<extToolkit:RichTextBox Text="{Binding Notes, UpdateSourceTrigger=PropertyChanged}" Name="rTextBoxQuestion" Margin="0,15,0,0" MinWidth="150" />

None of them fix the problem.

Mar 10, 2011 at 8:39 PM

This error is occuring in the PresentationFramework.dll.  Check you Debug -> Exception dialog in Visual Studio.  Make sure you have the Common Language Runtime Exception unchecked.  See if that helps.  If may be related to this bug reported to Microsoft.

https://connect.microsoft.com/VisualStudio/feedback/details/631925/textrange-save-throws-formatexception-when-saving-rtf

What version are you using? Let me know if that helps.

Mar 10, 2011 at 9:12 PM

The CLRE is unchecked at "Thrown" and checked at "User-unhandled". Unchecking the userunhandled part did not help. I am using VS2010, NET 4.0, and the latest Extended WPF Toolkit.

What I am trying to do is display the text from a richtextbox in a label/textblock/other richtextbox. Doing that for just the text is easy, but copying all the styling and the weigths is harder.

The extended richtextbox would solve my problem since the text is already styled in the RTF format.

Do you a way to copy the text from a richtextbox over with all the styling?

Mar 10, 2011 at 9:14 PM

Ahh.  SO the problem is you ar etrying to load the RTF from a different source.  Please provide the RTF you are trying to load.

Mar 10, 2011 at 9:19 PM

The problem I posted happens when I simply do this:

rTextBoxQuestion.Text = "any string";

I have already tried placing an RTF-styled example (the value of the notes property). It is later on that I want to actually copy text from one richtextbox to another, but I'm not even there yet :P

Mar 10, 2011 at 9:24 PM

I created a new empty application and defined my RTB like this:

<extToolkit:RichTextBox x:Name="_rtb" />

Then in code behind I set the text like this:

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            _rtb.Text = "any string";
        }

Works as expected.  It also works as expected when I do this in XAML only:

        <extToolkit:RichTextBox Text="Any String" />

Is it possible something else it cause the issue?  Could you please try to create a separate application to reproduce the issue?  I would like to help you solve this problem.

Mar 10, 2011 at 9:33 PM

Thank you very much.

I made a new project, and setting the text works without a single problem, but then I try to set the {Binding Notes}, and the error comes back. This is all the code in the project:

namespace RichTextBoxTesting
{
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private string _Notes = string.Empty;
        public string Notes
        {
            get { return _Notes; }
            set
            {
                _Notes = value;
                OnPropertyChanged("Notes");
            }
        }
        // Create the OnPropertyChanged method to raise the event
        protected void OnPropertyChanged(string _text)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(_text));
            }
        }
        public MainWindow()
        {
            InitializeComponent();
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            _rtb.Text = "any string";
        }
    }
}

<Window x:Class="RichTextBoxTesting.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:extToolkit="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit.Extended"
        Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
    <Grid>
        <extToolkit:RichTextBox x:Name="_rtb" Text="{Binding Notes}"/>
    </Grid>
</Window>

Mar 10, 2011 at 9:49 PM

I did just as you did.  Created a new .NET 4.0 WPF application.  I copied and pasted exactly what you had and no errors were thrown.  I then made some slight modification to use the notes property instead and it still works as expected.

XAML:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:extToolkit="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit.Extended"
        Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">

    <Grid>
        <extToolkit:RichTextBox Text="{Binding Notes}"/>
    </Grid>
</Window>
CS:
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;
        }

        private string _notes = string.Empty;
        public string Notes
        {
            get { return _notes; }
            set
            {
                _notes = value;
                OnPropertyChanged("Notes");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Notes = "any string";
        }
    }
I tested this with v1.3.0 and with the current source code.  I am not able to throw an error.
 
Mar 10, 2011 at 9:53 PM

Does this problem occur with a TextBox?  Can you download the source and step into the code to see where it is failing?

Mar 10, 2011 at 9:58 PM

Great! The "DataContext = this;"  part was crucial. Now that I added this my other project works as well :D

You've been a great help, I appreciate it. Without you fixing this would have taken an eternity.

Might I suggest the code you showed me to be put in the documentation of the RichTextBox? I'm sure people would appreciate a very basic example on how to get it working.

Again, thank you very much.

Apr 3, 2011 at 6:25 PM

I'm getting this same error, although I think I've got my code already doing the things you've suggested above.  The only difference is that my RichTextBox is in a View bound to a ViewModel, as follows:

From the view...

<TabItem Header="Content">
	<toolkit:RichTextBox 
		x:Name="_richTextBox" 
		Grid.Row="1" 
		Margin="10" 
		BorderBrush="Gray" 
		Padding="10" 
		Text="{Binding TextContent}" 
		ScrollViewer.VerticalScrollBarVisibility="Auto"/>
</TabItem>

From the ViewModel, which implements INotifyPropertyChanged...
public string TextContent
{
	get { return _Item.TextContent; }
	set
	{
		if (value != TextContent)
		{
			_Item.TextContent = value;
			OnPropertyChanged("TextContent");
		}
	}
}

It works fine until the RichTextBox loses focus, at which time the following exception is thrown: 

Unrecognized structure in data format 'Rich Text Format'.
Parameter name: stream

I downloaded the latest source (v1.3) as of 4/1/11 and built the assembly before referencing it.

The exception is being thrown in the toolkit's RtfFormatter class on this line:  tr.Load(ms, DataFormats.Rtf);

public void SetText(FlowDocument document, string text)
{
    TextRange tr = new TextRange(document.ContentStart, document.ContentEnd);
    using (MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(text)))
    {
        tr.Load(ms, DataFormats.Rtf);
    }
}

The text parameter has the following contents (some text redacted):

{\rtf1\ansi\ansicpg1252\deff0{\fonttbl{\f0\fnil\fcharset0 MS Sans Serif;}{\f1\fnil MS Sans Serif;}}
\viewkind4\uc1\pard\lang1033\f0\fs16 http://www.xxxxxxx.com\par
\par
Receipt for initial subscription\f1\par
\par
https://www.xxxxxxx.com/receipt.jsp?pid=26105\par
\par
\par
\f0 see xxxxxxx for login info\par
}

However, if I inspect the TextRange (tr), the value of its Text property is simply a Windows linefeed:  \r\n

I'm not sure if that's relevant, but I hope it will help get to the bottom of this.  Can you help?

Thanks!

Apr 3, 2011 at 6:32 PM

I just noticed in my previous post.  The tr.Text property I said was "\r\n" was from a breakpoint when the control was being loaded, which makes sense.  It contains the plain text of the RichText control.

Sorry for any confusion.

Apr 3, 2011 at 6:34 PM

Wow, after reading my previous post, I'm wondering where my brain is.  I meant to say, "When it loses focus, it contains the plain text of the RichText control."

Now I'm really sorry for all the confusion.  :-/

Apr 4, 2011 at 2:58 PM

Make sure you grab the latest source for v1.4.  It would be extremely helpful if you could provide an example that reproduces your issue.

Apr 4, 2011 at 3:59 PM

When is v1.4 going to be available?  I can't find it on this site.  I downloaded the latest source (wpftoolkit-71251.zip) and it is v1.3.

Apr 4, 2011 at 4:07 PM

Oh, you're using .NET 3.5.  I have not completely updated the source for .NET 3.5, but the issue you are reporting with the RichTextBox shouldn't be occurring.  Could you please provide a sample app?

Apr 4, 2011 at 7:59 PM

I have been using .NET 4.0.  I originally downloaded the "Extended WPF Toolkit Binaries" from http://wpftoolkit.codeplex.com/releases/view/58768, and that assembly's version info shows 1.3.0.

I then downloaded the latest source (I thought - Change Set 71251) from http://wpftoolkit.codeplex.com/SourceControl/list/changesets.  The target framework is ".NET Framework 4 Client Profile" and the assembly version is 1.3.0.0.

I can't find any reference to 1.4 anywhere, not even with a google search.

As to your request for a sample app, I will have to put something together when I have more time.  I was trying to get this work on a single view in a very large project, which I'd rather not provide.  I was hoping the source samples I gave above may be sufficient.  I'm leaning towards using another rich text editor at the moment, but I may still lean back in this direction, and if I do so, I will put together a little sample app I can send you.

Apr 5, 2011 at 1:00 AM

The current source code is version 1.4 for the .NET 4 framework.  If you are using the .NET 3.5 binaries, then it is still at v1.3 because it has not been updated yet.

Apr 5, 2011 at 1:20 AM

Ok - I've been using v1.4 then, although its assembly version info is still set at 1.3.0. If you take a look at it, you'll see what's causing the confusion.

Apr 5, 2011 at 1:21 AM
Edited Apr 5, 2011 at 1:23 AM

No, it is version 1.4.  Make sure you are using the Main branch and not the Release branch.

EDIT: Sorry, I am confused now.  Are you using .NET 3.5?  You said you were using 4.0 but if you are seeing it versioned as .1.3 then you must be using .NET 3.5.

Apr 5, 2011 at 2:06 AM
Ah, ok - finally found it. I was using the Release branch.

I built the Main branch, which is indeed v1.4.0, and after referencing that DLL, the problem was gone.

If there were instructions explaining all the different versions, etc., I missed them, but thanks, anyway, for your help!

Eric