Force WPF to update UI

Leave a comment

I’ve recently posted a Twitter Client to codeplex.com and I’ve been frustrated that I can’t seem to manually update when the tweet was posted. So I’ve started thinking a came up with this solution.

First create a Model that is derived from INotifyPropertyChanged and create the specific members:

public event PropertyChangedEventHandler PropertyChanged;

protected void OnPropertyChanged(string propertyName)
{
      if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

Define your properties: 

private DateTime _timeAgo;

public string TimeAgo
{
      get { return _timeAgo.ToRelativeTime(); //TweetSharp Extension }
      set
      {
            _timeAgo = DateTime.Parse(value);
            OnPropertyChanged(“TimeAgo”);
      }
}

Now define a System.Timers.Timer:

using System.Timers;
private Timer _timer = new Timer(){ Interval = 30000 //30000 miliseconds = 30 seconds };
private bool TimerFlag = true;

Modify your OnPropertyChanged method and add a new method to handle the Timer’s Elapsed event:

protected void OnPropertyChanged(string propertyName)
{
      if(TimerFlag)
      {
            _timer.Elapsed +=  new ElapsedEventHandler(_timer_Elapsed);
            _timer.Start();             
            TimerFlag = false;
      }
      if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

private void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
      OnPropertyChanged(“TimeAgo”);
}

Now I’m not sure how effective is this way but it seems to do the job for me. This only works for this kind of a scenario, because once the Model returns the TimeAgo, WPF’s DataBinding System doesn’t know if the property is changing over time. To it, it’s just a string. In other scenario’s when you change the property WPF’s DataBinding System knows that because of the OnPropertyChanged in set.

Simple, not sure if elegant but definitely works.

Can’t wait to hear your opinions on this.

Force WPF to update UI

2 Comments

I’ve recently posted a Twitter Client to codeplex.com and I’ve been frustrated that I can’t seem to manually update when the tweet was posted. So I’ve started thinking a came up with this solution.

More

Silveright 3D VS WPF 3D

Leave a comment

These days I’ve been messing around with Visual Studio 2010 Express for Windows Phone and I’ve noticed that the animation in the Phone List Application are pretty awesome so I’ve looked deeper into the bowels of the app and found out that it’s made using Projections. Basically it projects something into 3D space. Pretty nice for 3D-like applications. In this blog post I will add more as I find more interesting stuff to post. So far I know that you can’t project things in WPF. I’ll try to find out how to do it properly in Silverlight, then try it in WPF.

Stay tuned. More to come…

Silveright 3D VS WPF 3D

1 Comment

These days I’ve been messing around with Visual Studio 2010 Express for Windows Phone and I’ve noticed that the animation in the Phone List Application are pretty awesome so I’ve looked deeper into the bowels of the app and found out that it’s made using Projections. Basically it projects something into 3D space. Pretty nice for 3D-like applications. In this blog post I will add more as I find more interesting stuff to post. So far I know that you can’t project things in WPF. I’ll try to find out how to do it properly in Silverlight, then try it in WPF.

Stay tuned. More to come…

Writing a RSS feed reader – Day One

Leave a comment

I was literally thinking about what should be my first WPF app. As Pete Brown said in one of his articles you need to find a good starting app to get familiar with the technology. First I wanted to create an old (undone) app of mine made in WinForms, but it was a bit to complicated for WinForms also so I decide to go with a RSS feed reader.

Started Googleing for some demo apps to illustrate how to start with this kind of app but didn’t find anything that I liked.

After that I searched how to read RSS feed. I found that you can load the feed into an XDocument (System.Xml.Linq.XDocument) and get your info from there if you know how to work with xml files. The problem was that not all feeds have the same format. ‘Great!’ I thought another app goes to the dustbin, but I didn’t want to give up that easily and found out that .NET has a special namespace that can handle Syndication feeds like RSS and Atom: System.ServiceModel.Syndication. In this namespace I found the SyndicationFeed class and from there I can use it to read the feed. Great stuff!

After all of this I started to think how the hell I’m going to store my feeds. After a great amount of thinking I found out that storing them into the App Settings was the best way to do it. One more problem solved. Another problem comes up. I need to store both the feed title and the feed address for later use. Great another problem arose. Started to store the feed title and the feed address into the same setting and them split them using the String.Split method but that proved ineffective for the following reason: I used ‘_’ (underscore) as the split char, but that isn’t recommended because what happens when the feed title or the feed address contains an underscore. I would’ve got an IndexOutOfRange at best or worse incorrectly formatted strings in my settings.

How to solve this issue? Simple: put the title and the address on two separate settings and then use the StringCollection (System.Collections.Specialized) class’s IndexOf method to get the index of the title and them retrieve the address at the same index (as you add the feed title and feed address at the same time in the settings, you wont get mix-up indexes). After solving all of these issues is time to figure out how to populate the feed list, get the feeds and display them somewhere. I’m at this stage of development. Multi-threading will be involved as it takes some time to get the feed from the web. Error-handling will be somewhat painful but who said that this kind of app will be easy?

As I get a working alpha of my app I’ll post it on Google Project or Codeplex or maybe both and get some user feedback.

Here are some previews:

image UI mock-up (will be restyled)

image Code so far…

image Code so far… II

Looking forward for some feedback.

Writing a RSS feed reader – Day One

Leave a comment

I was literally thinking about what should be my first WPF app. As Pete Brown said in one of his articles you need to find a good starting app to get familiar with the technology. First I wanted to create an old (undone) app of mine made in WinForms, but it was a bit to complicated for WinForms also so I decide to go with a RSS feed reader.

Started Googleing for some demo apps to illustrate how to start with this kind of app but didn’t find anything that I liked.

After that I searched how to read RSS feed. I found that you can load the feed into an XDocument (System.Xml.Linq.XDocument) and get your info from there if you know how to work with xml files. The problem was that not all feeds have the same format. ‘Great!’ I thought another app goes to the dustbin, but I didn’t want to give up that easily and found out that .NET has a special namespace that can handle Syndication feeds like RSS and Atom: System.ServiceModel.Syndication. In this namespace I found the SyndicationFeed class and from there I can use it to read the feed. Great stuff!

After all of this I started to think how the hell I’m going to store my feeds. After a great amount of thinking I found out that storing them into the App Settings was the best way to do it. One more problem solved. Another problem comes up. I need to store both the feed title and the feed address for later use. Great another problem arose. Started to store the feed title and the feed address into the same setting and them split them using the String.Split method but that proved ineffective for the following reason: I used ‘_’ (underscore) as the split char, but that isn’t recommended because what happens when the feed title or the feed address contains an underscore. I would’ve got an IndexOutOfRange at best or worse incorrectly formatted strings in my settings.

How to solve this issue? Simple: put the title and the address on two separate settings and then use the StringCollection (System.Collections.Specialized) class’s IndexOf method to get the index of the title and them retrieve the address at the same index (as you add the feed title and feed address at the same time in the settings, you wont get mix-up indexes). After solving all of these issues is time to figure out how to populate the feed list, get the feeds and display them somewhere. I’m at this stage of development. Multi-threading will be involved as it takes some time to get the feed from the web. Error-handling will be somewhat painful but who said that this kind of app will be easy?

As I get a working alpha of my app I’ll post it on Google Project or Codeplex or maybe both and get some user feedback.

Here are some previews:

image UI mock-up (will be restyled)

image Code so far…

image Code so far… II

Looking forward for some feedback.

WPF Animation using DoubleAnimationUsingKeyFrames

Leave a comment

Every body knows that Windows Presentation Foundation provides better support for UI than WinForms does in .NET 3.5 (and RC .NET 4).

You can make very beautiful application UI using Visual Studio 2008 (or the new Visual Studio 2010), but this requires very good knowledge of XAML or use other WPF design based application like Microsoft Expression Blend. I for one don’t afford Blend and had to rely entirely on Visual Studio 2010. That’s my way of learning WPF design. Code and if I get no errors see what the code does.

In this post I’ll show how to make a button “disappear” from a window and come back using a Storyboard that contains a DoubleAnimationUsingKeyFrames.

Setting up the window and button

Right open up Visual Studio 2010 RC1 (Visual Studio 2008 Pro and Express editions will work just as well) and create a new project. From the New Project Window select Windows from your language of choosing and select a WpfApplication.

image

Visual Studio will create all the necessary files and open up your MainWindow.xaml in split mode (where you have the design at the top and the XAML at the bottom) with the following code:

<Window x:Class="WpfAnimationUsingKeyFrames.MainWindow"
        xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;
        xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;
        Title=”MainWindow” Height=”350″ Width=”525″>
   

   

Now lets add a button to our window. Add the following markup:

<Button x:Name=”Move”
        Content=”Move!”
        Margin=”3″ Padding=”10″
        HorizontalAlignment=”Center”
        VerticalAlignment=”Center”>

We’re done with setting up the window. So for you should have the following result:

image

Setting up RenderTransform

Now that we have our up we should add some RenderTransform properties to our button. We need to do this otherwise we won’t have what to animate in our storyboard when we’ll set up later.

Between your tags add the following markup:

               

Great! (Cheering up myself for typing this much so far) Now we have what to animate when we write our storyboard.

Setting up the Storyboard

Now that we have our button and the button is ready to accept render transformations lets write the storyboard.

Right before the tag (which is the opening tag for our grid) add the following markup:

We’ll define our storyboard in the windows resources. Not sure, but I think this is the only. If some WPF developer will scream in the comments that this is all wrong, sorry, but this is how it worked for me.

Moving on. Time to finally write the storyboard. I’ll write to whole markup and explain everything afterwards. It’s not complicated just bare with me on this. Between the Window.Resources tags write the following markup:

    <DoubleAnimationUsingKeyFrames BeginTime="00:00:00"
                                   Storyboard.TargetName=”Move” Storyboard.TargetProperty=”(UIElement.RenderTransform).(TranslateTransform.X)”>
       
       
       
       
       
   

Time for the explaining part. Hope I don’t get this wrong.
So first of all the x:Key property of a storyboard is required in everything you declare in your windows resources. If you don’t do that you’ get an error.
Every storyboard needs to contain an Animation. It’s the only child the container of a storyboard accepts. If you attempt to add a button to a storyboard you get an error.
There are several animation’s depending on what kind of property values are your trying to animate. In this case we’re animating a Double value in the TranslateTransform’s X property, which is a Double. That’s why we have DoubleAnimation. The UsingKeyFrames is there because we are obviously using KeyFrames to animate. I’m using key frames because  I’ve done some work in Adobe After Effects and I’m to animating with Key Frames.

The BeginTime property of the animation is when the animation starts. This property is a TimeSpan value. XAML is intelligent enough convert the “00:00:00” string to TimeSpan.
Storyboard.TargetName sets the storyboard target to an element name, in this case to our Button which has x:Name property set to “Move”.
Storyboard.TargetProperty sets the storyboard target property to a property of the element which has the name set in Storyboard.TargetName property. The value of this property is bit hard to add at first but when you know how to determine what type of property is any property will be easy. If you hover over property name in Visual Studio you get a tooltip that says the full length of the property.

image

Always remember to add the property into brackets (e.g. “(PropertyPath)” ). XAML will always convert to see it’s a correct property name and give an error if it’s not.
Once you told the animation what element to target and what property of that element to animate, it’s time to set up the key frames.
In the DoubleAnimationUsingKeyFrames tags add a SplineDoubleKeyFrame. You can add as many of these as you want.
The KeyTime and Value properties say that at the value of the KeyTime, the Value of the property specified in the Storyboard.TargetProperty is the same with Value. The thing is that between “00:00:00” and “00:00:00.0100” the value animates to 10. At time “00:00:00.0050” you won’t have 0. You’ll have a value between 0 and 10. Pretty nice eh? The same principle applies to al SplineDoubleKeyFrame’s.

Now that we have defined our Storyboard it’s time to tell to button when to animate.

Starting the Storyboard

Just right before the end of tag add the following markup:

   
       
   

Now when you click the button it will animate. Press F5 to debug and see what we have created.

The storyboard can be started in the Code-behind. If you want to add more code when you click the button you need set button’s Click event to an event handler. Remove the markup I told you to write above and modify the to show the following:
<Button x:Name="Move"
        Content=”Move!”
        Margin=”3″ Padding=”10″
        HorizontalAlignment=”Center”
        VerticalAlignment=”Center”
        Click=”Move_Click”>
   
       
   

Now in the code-behind write to following code in Window Class:
private void Move_Click(object sender, RoutedEventArgs e)
{
    (Resources[“Move”] as Storyboard).Begin();
}

Be sure to add the following reference in your using section:
using System.Windows.Media.Animation;

Done

That’s it! You’re done. Hope you found this post helpful as I found it fun to write. If I made some mistakes in my explanations or if I said some wrong/stupid things please do say it in the comments.

Looking forward for some feedback.

Full XAML with EventTriggers:

<Window x:Class="WpfAnimationUsingKeyFrames.MainWindow"
        xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;
        xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;
        Title=”MainWindow” Height=”350″ Width=”525″>
   
       
            <DoubleAnimationUsingKeyFrames BeginTime="00:00:00"
                                           Storyboard.TargetName=”Move” Storyboard.TargetProperty=”(UIElement.RenderTransform).(TranslateTransform.X)”>
               
               
               
               
               
           
       
   
   
        <Button x:Name="Move"
                Content=”Move!”
                Margin=”3″ Padding=”10″
                HorizontalAlignment=”Center”
                VerticalAlignment=”Center”>
           
               
           
           
               
                   
               
           
       
   

Full XAML with Click Event & Full Code-behind

XAML:
<Window x:Class="WpfAnimationUsingKeyFrames.MainWindow"
        xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;
        xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;
        Title=”MainWindow” Height=”350″ Width=”525″>
   
       
            <DoubleAnimationUsingKeyFrames BeginTime="00:00:00"
                                           Storyboard.TargetName=”Move” Storyboard.TargetProperty=”(UIElement.RenderTransform).(TranslateTransform.X)”>
               
               
               
               
               
           
       
   
   
        <Button x:Name="Move"
                Content=”Move!”
                Margin=”3″ Padding=”10″
                HorizontalAlignment=”Center”
                VerticalAlignment=”Center”
                Click=”Move_Click”>
           
               
           
       
   

Code-behind:

using System.Windows;
using System.Windows.Media.Animation;

namespace WpfAnimationUsingKeyFrames
{
    ///

    /// Interaction logic for MainWindow.xaml
    ///

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Move_Click(object sender, RoutedEventArgs e)
        {
            (Resources[“Move”] as Storyboard).Begin();
        }
    }
} //Removed unused using;

Older Entries