Binding to a RichEditBox

May 25, 2013 at 8:05 am | Posted in Cpp, Windows 8 | Leave a comment
Tags: ,

The RichEditBox control does not have a Text property so reading an writing simple text is more complex than a simple TextBox or TextBlock. Here are some C++/CX code examples:

Read text:

	String^ tempOutput;
	myRichEditBox->Document->GetText(Windows::UI::Text::TextGetOptions::None, &tempOutput);
	result->Text = tempOutput;

Write text:

	myRichEditBox->Document->SetText(Windows::UI::Text::TextSetOptions::None, "Hello World");

But what about data binding? The solution is to create an attached property.


namespace WUX = Windows::UI::Xaml;

namespace AttachedProperty
	public ref class MainPage sealed

		virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;

	public ref class Attached sealed : public WUX::DependencyObject {
		static WUX::DependencyProperty^ _TextProperty;

		static property WUX::DependencyProperty^ TextProperty
			WUX::DependencyProperty^ get() {
				return _TextProperty;
		static Platform::String^ Attached::GetText(WUX::UIElement^ element) {
			return (Platform::String^)element->GetValue(_TextProperty);
		static void Attached::SetText(WUX::UIElement^ element, Platform::String^ value) {

		static void OnTextChanged(WUX::DependencyObject^ d, WUX::DependencyPropertyChangedEventArgs^ e);


using namespace AttachedProperty;

using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
using namespace Windows::UI::Xaml::Interop;
using namespace Windows::UI::Xaml::Documents;


void MainPage::OnNavigatedTo(NavigationEventArgs^ e)
	(void) e;	// Unused parameter

DependencyProperty^ Attached::_TextProperty = DependencyProperty::RegisterAttached(
	ref new PropertyMetadata("",
	ref new PropertyChangedCallback(&Attached::OnTextChanged))	

void Attached::OnTextChanged(DependencyObject^ d, DependencyPropertyChangedEventArgs^ e)
	auto Box = (RichEditBox^) d;
	auto s = (Platform::String^)(e->NewValue);
	Box->Document->SetText(Windows::UI::Text::TextSetOptions::None, s);

Then to test, here is some XAML

        <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock x:Name="mySource">Hello World</TextBlock>
        <RichEditBox Width="500" Height="200" local:Attached.Text="{Binding Text, ElementName=mySource}"/>

Create a free website or blog at
Entries and comments feeds.