Sunday, March 31, 2013

Windows Store App… How to set focus on a textbox

A common task in UI development is setting the focus on a textbox when navigating to a particular screen. When doing this on a Windows 8 application, a lot of developers try to do this inside the OnNavigatedTo event handler. This does not work. To set the focus on a textbox when the page is hit, call the focus method on the particular textbox inside the loaded event handler… That should do it.

<common:LayoutAwarePage
x:Name="pageRoot"

Loaded="pageRoot_Loaded_1">



private void pageRoot_Loaded_1(object sender, RoutedEventArgs e)
{
this.txtName.Focus(FocusState.Programmatic);
}



Hope this helps. Happy Coding!



Friday, March 29, 2013

ChangeAwareContentControl–How to know when the content changes in a ContentControl

I am working on an application where I have a ContentControl, and I need to know when the content changes. My initial thought was to add an event handler for the ContentChanged event. I came to find out that the ContentControl does not fire a ContentChanged event.

My solution was to create a control derived from content control that fires that particular event. It is working quite nicely, so I thought I would share. I hope it helps you out. It’s a small amount of code, but it does the trick.

    public class ChangeAwareContentControl : ContentControl
{
static ChangeAwareContentControl()
{
ContentProperty.OverrideMetadata(
typeof(ChangeAwareContentControl),
new FrameworkPropertyMetadata(
new PropertyChangedCallback(OnContentChanged)));
}

private static void OnContentChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
ChangeAwareContentControl mcc = d as ChangeAwareContentControl;
if (mcc.ContentChanged != null)
{
DependencyPropertyChangedEventArgs args
=
new DependencyPropertyChangedEventArgs(
ContentProperty, e.OldValue, e.NewValue);
mcc.ContentChanged(mcc, args);
}
}

public event DependencyPropertyChangedEventHandler ContentChanged;
}


Here is how you use it in xaml.



<controls:ChangeAwareContentControl ContentChanged="ContenChangedHandler"/>


Thursday, March 28, 2013

BitmapImage.BeginInit()

A very common error new UI developers make is trying to create new BitmapImages without properly initializing them.

All property changes made to a BitmapImage must be made between the BeginInit() and EndInit() calls. Every property change made after the EndInit() call is ignored.

Here is a small code snippet on how to properly create a new bitmap image and set that as the source of an Image object.

// Define a BitmapImage.
Image myImage = new Image();
BitmapImage bi = new BitmapImage();

// Begin initialization.
bi.BeginInit();

// Set BitmapImage properties. (CacheOption,CreateOptions… etc.)

// End initialization.
bi.EndInit();


myImage.Source = bi;