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.

.h

namespace WUX = Windows::UI::Xaml;

namespace AttachedProperty
{
	
	public ref class MainPage sealed
	{
	public:
		MainPage();

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

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

	public:
		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) {
			element->SetValue(_TextProperty,value);
		};

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

.cpp

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;


MainPage::MainPage()
{
	InitializeComponent();
}


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


DependencyProperty^ Attached::_TextProperty = DependencyProperty::RegisterAttached(
	"Text", 
	TypeName(String::typeid),  
	TypeName(Attached::typeid),
	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}"/>
    </Grid>

First published Win 8 app

October 25, 2012 at 7:40 am | Posted in Uncategorized | Leave a comment

I just released my first application for Windows 8. QuakeView is an app that displays USGS earthquake data on a Bing map. It has the ability to download recent events in the background, display them on live tiles on the Start page and send toast notifications for significant events. I originally wrote the app in HTML5/CSS3/JavaScript in the Developer Preview to learn about this method of app development for Win 8 but switched to XAML/C# when the Bing Maps SDK became available.

The effort has been a terrific exercise in learning many of the key concepts and techniques for writing Win 8 apps.

Here is a link to the app int the Store.

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.

<body>
    <div id="myTemplate" data-win-control="WinJS.Binding.Template">
        <div data-win-bind="innerText: id"></div>
    </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')}">
    </div>
</body>
(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);
        WinJS.UI.processAll();
    });

})();

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:


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


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

    var labelSource = WinJS.Binding.as(person);
   
    WinJS.strictProcessing();

    WinJS.Utilities.ready(function(){
        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() {
        labelSource.name = "John";
        labelSource.city = "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
Tags:

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;
        instLocation.getFileAsync(path)
        .then(function (file) {
            return Windows.Storage.FileIO.readTextAsync(file);
        }).done(function (myText) {
            console.log(myText);
        });
    }
Next Page »

Blog at WordPress.com.
Entries and comments feeds.