Showing posts with label WPF. Show all posts
Showing posts with label WPF. Show all posts

Tuesday, March 1, 2011

WPF - Passing Arguments to Timer.Tick

Recently I worked on a projected that needed to animate objects based on a timer. I wanted to write a generic timer handler to perform an operation on the object passed in to the timer. Initially I tried messed with EventArgs passed to the event handler, but turns out there is an easier way - using the "Tag" property:

// Note: You can have only one DispatchTimer object per class
private DispatcherTimer _timer;

MyClass()
{
    // Timer Start Code
    var myObject = new SomeObject();
    _timer.Interval = TimeSpan.FromMilliseconds(700);
    _timer.Tag = myObject ;
    _timer.Tick += TimerTickEventHandler;
    _timer.Start();
}

private void TimerTickEventHandler(object  sender, EventArgs e)
{
    var timer = (DispatcherTimer)sender;
    var myObject = (SomeObject)timer.Tag;
    // now you can use myObject
    timer.Stop();
}

Monday, February 28, 2011

Using Code Behind For Property Binding in WPF

This is a very common thing in WPF, but after being away from WPF for some time, I often have to look it up. In order to bind to properties in the code behind, you need to set the DataContext of the window to "self" as per example below:

<Window x:Class="MyProject.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        DataContext="{Binding RelativeSource={RelativeSource Self}}">

        <Label Content="{Binding StatusText}"/>
</Window>

Now you can bind to a dependency property like this in your code behind:

public string StatusText
{
    get { return (string)GetValue(StatusTextProperty); }
    set { SetValue(StatusTextProperty, value); }
}

public static readonly DependencyProperty StatusTextProperty =
    DependencyProperty.Register("StatusText", 
typeof(string), typeof(MainWindow), new UIPropertyMetadata(""));