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}"/>

Bing Maps for Metro Gotcha

July 6, 2012 at 4:12 pm | Posted in Metro, Visual Studio 2011, Windows 8 | Leave a comment

Just ran into a mysterious behavior when trying to use the Bing Maps API for C#/XAML Metro applications. I have several apps that use this API and seem to be working well. This morning, I tried to make another test app and Visual Studio said it could not render the map. The error message indicated that the class was not registered. I doubled checked that the Build configuration was set to Debug with a specific processor type and that I had the Bing Maps and C++ runtime in my resources. I cleaned the solution and rebuilt it with no success.

Finally, I deleted the Bing Maps resource from the solution. When I re-added it, the problem cleared.

(An update: Another solution that I had given up on before discovering this trick suddenly started working after closing and restarting Visual Studio.)

This is one thing that I dislike about XAML development. There is a lot of magic that is going on behind the scenes. It appears that if things are not just so, the solution can break. Fragile. Reminds me of the early days of XAML/WPF in Visual Studio (maybe even for WinForms, I don’t know) but there were times that you could screw up a name of something in your project and the designer would go nuts. No amount of rework would recover. The only recourse was to start over with a fresh template and carefully reconstruct the project piece by piece.

Minimal ListView Binding

May 9, 2012 at 7:51 am | Posted in HTML/JavaScript, Metro, Visual Studio 2011, Windows 8 | Leave a comment

Sometimes it is hard to see the forest for all of the trees. In learning the HTML5/JavaScript platform, I’ve relied on the plumbing of the Blank Application template in Visual Studio without understanding all of the functions. I recently responded to a forum query with an example of binding and updating a ListView with a super simple JavaScript that did not use the template.

This code has a ListView and a Button. The ListView is initialized from an array using a Binding.List. The bindings are declared in the markup. The Button click event triggers the addition of a new item to the list.

    <div id="myTemplate" data-win-control="WinJS.Binding.Template">
        <div data-win-bind="innerText: id"></div>
    <button id="add">Add</button>
    <div id="myListView" data-win-control="WinJS.UI.ListView" data-win-options="{itemDataSource: Dataex.itemList.dataSource, itemTemplate:select('#myTemplate')}">
(function () {
    "use strict";

    var dataArray = [{ id: "one" }, { id: "two" }]
    var dataList = new WinJS.Binding.List(dataArray);

    var p ={itemList: dataList};
    WinJS.Namespace.define("Dataex", p);

    function addItem() {
        dataList.push({ id: "three" });

    WinJS.Utilities.ready(function () {
        document.getElementById("add").addEventListener("click", addItem, false);


Simple data binding example

April 30, 2012 at 10:06 am | Posted in HTML/JavaScript, Metro, Windows 8 | Leave a comment

{Code updated to reflect changes in Release Preview.}

I was trying add a simple piece of markup that had text elements bound to an object, but just could not get it to work the way I wanted, i.e. declare a binding source in the markup. By looking at the samples, I could use WinJS.BindingAll(element, object), but for some reason failed with data-win-bindsource in the markup. Finally, I did a Google search on “data-win-bindsource” and ran across a post in November 2011 that was exactly what I was trying to do. It turns out that the answer provider was me!

So for the sake of others who are trying to do the same thing and for pounding this nugget into my own brain, here is the example:

    <div class="fixed-layout">
        <div data-win-bindsource="">
            <div data-win-bind="innerText: x"></div>
        <button id="myButton">

(function () {
    "use strict";
    var person = {
        name: "Tom",
        city: "Boston"

    var labelSource =;

        WinJS.UI.processAll().then(function () {
            var elem = document.querySelector("#complexLabel");
            WinJS.Binding.processAll(elem, labelSource);

        var lab = document.getElementById("complexLabel");
        document.getElementById("action").addEventListener("click", changeLabel, false);

    function changeLabel() { = "John"; = "New York";

    //Make names public with namespace so that HTML file can see them
    WinJS.Namespace.define('test', {
        labelSource: labelSource

Reading a text file from the app package

April 23, 2012 at 5:37 pm | Posted in HTML/JavaScript, Metro, Windows 8 | Leave a comment

This is an example of how to read a text file that is embedded in the app package.

 //Read a text file in the 'data' folder in the app package.
    //Outputs the contents to the console
    function getDataFromPackage(fileName) {
        var myPackage = Windows.ApplicationModel.Package.current;
        var instLocation = myPackage.installedLocation;
        var path = "data\\" + fileName;
        .then(function (file) {
            return Windows.Storage.FileIO.readTextAsync(file);
        }).done(function (myText) {

Background task pollution

April 22, 2012 at 1:21 pm | Posted in HTML/JavaScript, Metro, Windows 8 | Leave a comment

I am developing a Metro HTML/JavaScript application which uses a background task to notify the user of updates to some data that is collected periodically. Initally, the background task simply read the data, did some filtering and sent a tile notification. This all seemed to be working well. When I added a toast notification; however, I began to see some strange behavior.

First, I noticed that when the background task fired based on a timer, that dozens of processes seemed to appear in the Visual Studio debugger. Second, I found that the toast was triggered multiple times for each interval. Of course, this continued even if the program was no longer running. It occurred after a reboot also.

My suspicion was that the background task was registered multiple times. My program was configured to register the background task every time it was launched. I assumed that the system would just overwrite the previous registration with the new one. It appears, though that each registration is added to a list of registrations even if they are identical. After numerous debug sessions, these registrations were adding up. I was polluting the background task manager.

The programmatic solution to this problem is to unregister all of the tasks associated with the program using the following routine:

function unregisterBackgroundTasks(taskName) {
        // Loop through all background tasks and unregister any with the taskName
        var iter = Windows.ApplicationModel.Background.BackgroundTaskRegistration.allTasks.first();
        var hascur = iter.hasCurrent;
        while (hascur) {
            var cur = iter.current.value;
            if ( === taskName) {
            hascur = iter.moveNext();

This seems to work well but I do not know if there is a way to clear this “pollution” of the background task manager outside of the program except that background tasks are unregistered when a program is uninstalled.

Next Page »

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