Wednesday, May 25, 2011

Data Binding improvements in WPF 4.0

In this post i will explain what are the new changes and improvements done in Data Binding in WPF 4.0

InputBinding

InputBinding was available in previous versions and the limitation was not able to bind Command property of InputBinding class. In WPF 4.0, InputBinding.Command property implemented as Dependency Property. Not only Command but KeyBinding.Key, KeyBinding.Modifiers, MouseBinding.MouseAction, InputBinding.CommandParameter and InputBinding.CommandTarget properties also implemented as Dependency Property so these all properties are now bindable.

Please have a look on below example of binding command property of InputBinding.

<Window x:Class="WPFTestApplication.InputBindingsImprovements"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WPFTestApplication"
        Title="Command Binding Improvements" Height="200" Width="200">
<Grid>
<Button Content="Hit Me!"
    Command="{Binding MyCommand}"           
    Height="30" Width="150">
    <Button.InputBindings>
        <KeyBinding
            Command="{Binding MyCommand}"
            Key="{Binding MyCommand.KeyGesture}"
            Modifiers="{Binding MyCommand.ModifierKey}" />
        <MouseBinding
            Command="{Binding MyCommand}"
            MouseAction="{Binding MyCommand.MouseActions}" />
    </Button.InputBindings>
</Button>
</Grid>
</Window>

CodeBehind

public partial class InputBindingsImprovements : Window
{
    public InputBindingsImprovements()
    {
        InitializeComponent();
        mycommand = new BaseCommand((str) => MessageBox.Show("Hello"));
        mycommand.KeyGesture = Key.H;
        mycommand.ModifierKey = ModifierKeys.Control;
        mycommand.MouseActions = MouseAction.RightClick;
        DataContext = this;
    }
    private BaseCommand mycommand;
    public BaseCommand MyCommand
    {
        get { return mycommand; }
    }

}
public class BaseCommand : ICommand
{
    Action<object> actionDelegate;
    public event EventHandler CanExecuteChanged;
    public BaseCommand(Action<object> myDelegateAction)
    {
        actionDelegate = myDelegateAction;
    }
    public void Execute(object action)
    {
        actionDelegate(action);
    }
    public bool CanExecute(object canexecute)
    {
        return true;
    }
    public Key KeyGesture { get; set; }
    public ModifierKeys ModifierKey { get; set; }
    public MouseAction MouseActions { get; set; }
}


Output
























In above example, I have bound MyCommand to Button so when user I click on button the MessageBox will appear. I have also bound the same Command with Key and Modifier to KeyBinding and MouseBinding. So when user Press Ctrl+H as well RightMouse Click on the Button the same Messagebox will appear.


Dynamic Object Binding

In WPF 4.0, you can databind dynamic (runtime known) properties. It supports binding to objects which implements IDynamicMetaObjectProvider or inherited from DynamicObject. DynamicObject class provides dynamic behavior at runtime. You can set or get members value by overriding TryGetMember or TrySetMember method.

<Window.Resources>
    <local:SimpleDynamicClass x:Key="MyInstance" />
</Window.Resources>
<StackPanel DataContext="{StaticResource MyInstance}">
    <Label Content="Enter anything:" />
    <TextBox Text="{Binding MyType}" Margin="5" Width="200"
                HorizontalAlignment="Left"/>
    <Button Content="Click Me!" Click="Button_Click"
            HorizontalAlignment="Left"
            Height="25" Width="100" Margin="5"/>
    <Label Name="ResultLabel" Margin="5" />
</StackPanel>

Code Behind
public class SimpleDynamicClass : DynamicObject
    {
        public string MyName;
        public override bool TryGetMember(GetMemberBinder binder, 
                                          out object result)

        {
            result = MyName;
            return true;
        }
        public override bool TrySetMember(SetMemberBinder binder,
                                          object value)
        {
            MyName = value.ToString();
            return true;
        }
    }

public partial class NewBindings : Window
    {
        public NewBindings()
        {
            InitializeComponent();
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            dynamic MyInstance = FindResource("MyInstance");
     ResultLabel.Content =  MyInstance.MyType;
        }
    }

Output
















In above example, I have created one class named SimpleDynamicClass derived from DynamicObject and bind its property with TextBox. On Button click I am retrieving the same instance value from resource and showing it in to the label.

Bindable Run Element

You can read about Bindable Run in my separate post here.


Saturday, May 21, 2011

Windows 7 Task bar programming with WPF 4.0


Windows 7 Task Bar has so many new improved features and you can take full advantage of all features using WPF 4.0. You can customize Windows 7 task bar features like

  • Overlay Icons
  • Thumbnail Buttons
  • Progress Bar
  • Jump Lists

Overlay Icons

You can display application’s status using Overlay Icons. Overlay icons are small icons (size around 16 x 16 pixels) and can be set over your application’s icon. When you want to display your application’s status like your application is connected with service or playing audio or paying video etc. so you don’t need to replace your application’s icon instead you can set just overlay icon.

You just need to set any icon to overlay property of TaskbarItemInfo to display overlay icon in task bar along with application's icon. This also can be set from code behind based on different conditions.

<Window.TaskbarItemInfo>
  <TaskbarItemInfo 
          Overlay="/WPFApplication1;component/Images/video.ico" />
</Window.TaskbarItemInfo>





You can see video frame icon (small icon) on top of application icon is called as overlay icon. Based on overlay icon's status use can identify application’s status. As per above image user can easily understand that application is running some video. Likewise you can set different overlay icons based on different application’s state like running, stop, connected etc.  

Thumbnail Buttons

Thumbnail Buttons are small buttons can be placed over application icon. This can be displayed when you move mouse over the application’s task bar icon. Using these buttons you can interact with your application. These Thumbnail buttons interacts with your application from task bar and for that you need to add similar code which you may have already applied for existing button. Thumbnail buttons can be added in TaskbarItemInfo. 


The best example for thumbnail button is Media player in windows 7. You can play/pause media using thumbnail buttons from task bar. In below example I have created one Image Navigation Application and use Thumbnail button to navigate images.

<Window.TaskbarItemInfo>
<TaskbarItemInfo Overlay="/WPFApplication1;component/Images/video.ico"
                 x:Name="MyTaskItem"
                 ProgressState="Normal">
    <TaskbarItemInfo.ThumbButtonInfos>
        <ThumbButtonInfo x:Name="thumbPrevious"
              Description="Previous"
              ImageSource="/WPFApplication1;component/Images/rewind.ico"
              Click="thumbPrevious_Click" />
        <ThumbButtonInfo x:Name="thumbNext"
              Description="Next"
              ImageSource="/WPFApplication1;component/Images/forward.ico"
              Click="thumbNext_Click"/>
    </TaskbarItemInfo.ThumbButtonInfos>
</TaskbarItemInfo>
</Window.TaskbarItemInfo> 

private void thumbPrevious_Click(object sender, EventArgs e)
{
      setPreviousImage();
}
private void thumbNext_Click(object sender, EventArgs e)
{
      setNextImage();
}






















In first image you can see two Thumbnail buttons below the preview of  running application in task bar when you hover mouse over the application icon and in second image you can see the running application preview. 

This application used to navigate images. I can move to next and previous images using next/previous button and same time i can see preview of my current image. I have created two thumbnail buttons and applied functionality similar to Next/Previous button. Now i can navigate image from task bar only don't need to open application and click on next/previous button.

So using thumb button I can interact with application and do some important activities from task bar itself instead of doing it from application. You can use thumb button in your application for different purposes like start/stop service, Play/Pause Video etc.

Progress Bar

You can display progress of your application in task bar icon. For example when downloading is in progress you can see downloading progress from application’s icon in task bar. So you don't need to open application to check download progress. You can specify four types of progress state for you progress bar.

  • Normal - Progress bar icon is green and shows normal progress
  • Paused - Progress bar icon is yellow and shows paused progress
  • Indeterminate - Progress bar icon is green and shows indeterminate state.
  • Error – Progress bar icon is Red and shows error in progress.

<Window.TaskbarItemInfo>
    <TaskbarItemInfo x:Name="MyTaskItem"
                     ProgressState="Normal">
    </TaskbarItemInfo>
</Window.TaskbarItemInfo>


To specify current progress of your application use ProgressValue property of TaskBarItemInfo. ProgressValue property accepts value between 0 to 1. You can use BackgroundWorker to update ProgressValue property and let user notify when completed using RunWorkerCompleted event of BackgroundWorker. You can read more about BackgroundWorker here. It is not compulsory to use BackgroundWorker to set ProgressValue but recommended way to use. You can also use Timer instead. In below example for demo purpose i used timer to set ProgressValue.

void timer_Tick(object sender, EventArgs e)
{
      if (progresscount <= 100)
      {
    MyTaskItem.ProgressValue = (progresscount)/100;
           progresscount++;
      }
}






In above image you can see progress of your application in green color. So you can know how much progress is completed form task bar only. You don’t need to open application window to check progress.


JumpList

Jumplist is new feature of Windows 7 task bar and using WPF4 you can easily interact with this Windows7 Task bar feature. When you right click on application’s icon in task bar you can see few items under Task or Recent or most visited categories. Please have a look on below image





















Jump Lists can have two types of items Tasks and Paths. Tasks are nothing but shortcuts to other application and Paths are shortcuts to other file or folder. You can also enable built-in category called Recent and Frequent on you application’s Jumplist. To enable that you need to set ShowRecentCategory and ShowFrequentCategory properties to true in your application’s JumpList. You can add JumpList in your app.xaml file as well as in code behind.

<Application x:Class="WpfApplication1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="Windows7TaskBar.xaml">
<Application.Resources>
</Application.Resources>
<JumpList.JumpList>
    <JumpList ShowRecentCategory="True"
              ShowFrequentCategory="True">
        <JumpPath Path="D:\Temp\" CustomCategory="MyCategory" />
        <JumpTask ApplicationPath="C:\Windows\Notepad.exe"
                  IconResourcePath="C:\Windows\Notepad.exe"
                  Description="Open Notepad"
                  Title="Notepad" />
        <JumpTask ApplicationPath="C:\Windows\System32\Calc.exe"
                  IconResourcePath="C:\Windows\System32\Calc.exe"
                  Description="Open Calculator"
                  Title="Calculator" />
    </JumpList>
</JumpList.JumpList>
</Application>

















You can see in above output, two tasks Notepad and Calculator added when you right click on your application’s icon in task bar. Similarly you can see recent and frequent files of your application please have a look on below snapshot of word application.



















WPF4 provides good and powerful features to interact with Windows7 Task bar Features. Using JumpList features you can provide good user interface for user to interact with you application as well other applications.


Hope you like this post and have better understanding about WPF4 task bar features. Please post your queries/feedback/comments here in comments section.