Showing posts with label ObjectDataProvider. Show all posts
Showing posts with label ObjectDataProvider. Show all posts

Tuesday, February 1, 2011

WPF - Binding Method Parameters of ObjectDataProvider

In this post we will be discussing how we can use data returned by a method for WPF Binding in XAML using ObjectDataProvider. We will also be discussing how we can work around the requirement of WPF Binding to have a non-DependencyProperty based Binding target. Using non-Dependency properties as a Binding target. We will also shed some light on Binding to ObjectDataProvider instance instead of ObjectDataProvider.Data.

Let's create a sample WPF application ObjDataProvider_BindingMethodParameters. Add a class named ExponentCalculator. This class just has a public method getResult. This method receives two arguments. It just evaluates the second argument as exponent to the first argument and returns the result. It uses Pow static method of System.Math class.

namespace ObjDataProvider_BindingMethodParameters
{
using System;

class ExponentCalculator
{
public double getResult(double number, double exponent)
{
double result = Math.Pow(number, exponent);

return result;
}
}
}

Now we use the above class into action. We update the definition of MainWindow.xaml . We are using the same ObjectDataProvider as we have used in previous post. We are just using another feature of ObjectDataProvider. It can grab data from a method of a type. It also introduces a property Data which is used for Binding the data returned by the method.

It even allows to specify parameters to the method as you can see in the following code that we have specified two parameters. They are both of type double. We needed to add System namespace to use Double. We have specified it to use the alias sys which we are using to define types of method parameters.

<Window x:Class="ObjDataProvider_BindingMethodParameters.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:ObjDataProvider_BindingMethodParameters"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ObjectDataProvider ObjectType="{x:Type local:ExponentCalculator}"
MethodName="getResult" x:Key="expCalculator">
<ObjectDataProvider.MethodParameters>
<sys:Double>4</sys:Double>
<sys:Double>2</sys:Double>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
<Grid>
<TextBox Height="30" HorizontalAlignment="Left" Margin="69,12,0,0"
Name="textBoxNumber" VerticalAlignment="Top" Width="422"
Text="{Binding Source={StaticResource expCalculator}, Path=MethodParameters[0], BindsDirectlyToSource=True, Mode=OneWayToSource}"/>
<Label Content="Number" Height="33" HorizontalAlignment="Left" Margin="6,10,0,0"
Name="label1" VerticalAlignment="Top" Width="57" />
<TextBox Height="30" HorizontalAlignment="Left" Margin="69,51,0,0" Name="textBoxPower"
VerticalAlignment="Top" Width="422"
Text="{Binding Source={StaticResource expCalculator}, Path=MethodParameters[1], BindsDirectlyToSource=True, Mode=OneWayToSource}"/>
<Label Content="Power" Height="33" HorizontalAlignment="Left" Margin="6,49,0,0"
Name="label2" VerticalAlignment="Top" Width="57" />
<Label Content="Result" Height="33" HorizontalAlignment="Left" Margin="6,88,0,0"
Name="label3" VerticalAlignment="Top" Width="57" />
<TextBlock Height="31" HorizontalAlignment="Left" Margin="69,88,0,0" Name="textBlockResult"
Background="PaleTurquoise" VerticalAlignment="Top" Width="419" >
<TextBlock.Text>
<Binding Source="{StaticResource expCalculator}" />
</TextBlock.Text>
</TextBlock>
</Grid>
</Window>

Generally we have seen that Binding is defined on the Target element. But WPF has this requirement that the target properties must be dependency properties. So we can not define binding there. But we still want user to type some number in the two text boxes and get the result. In order to still fulfill the requirement, we are exploiting one of the WPF Binding mode, it is OneWayToSource. This is used for the Text properties of the two text boxes. Here Method parameter is considered as source and whatever data entered in the text boxes, would be available in MethodParameters collection.

Now when we Bind with an ObjectDataProvider, the binding takes place with Data property of ObjectDataProvider. WPF makes the data available in this property. Since Method Parameters are not from the Data itself how should we do that? Basically Binding allows this too. If we set BindsDirectlyToSource, it is bound to the ObjectDataProvider instance itself instead of the Data property of ObjectDataProvider. Since we need to show the data returned from the method, we are binding the ObjectDataProvider instance to the Text property of TextBlock using StaticResource markup extension. As we have discussed, this would bind to Data property of ObjectDataProvider instance.

Now lets run the application. It shows the MainWindow as follows:


We enter some data in the text boxes but it seems no evaluation is being done as the TextBlock showing the result is empty. In order to determine what is actually going on lets update the Visual Studio settings to be more watchful of the binding by enabling more restrictive Trace Settings for WPF Binding. Go to Tool -> Options in Visual Studio and set Tracing for DataBinding to All.


Now run the application and see the output window:


Now we see what is going on. Basically the Text property of TextBox is of type string. We need to convert the text entered to double so that correct method can be called. Let us define an IValueConverter for this purpose.

namespace ObjDataProvider_BindingMethodParameters
{
#region namespaces
using System;
using System.Windows.Data;
#endregion namespaces

[ValueConversion(typeof(string), typeof(double))]
public class doubleStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
//throw new NotImplementedException();
return value.ToString();
}

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
//throw new NotImplementedException();
double doubleValue = 0.0;

string strText = (value == null) ? string.Empty : value.ToString();

if (strText != string.Empty)
{
doubleValue = double.Parse(strText);
}

return doubleValue;
}
}
}

To use this converter, we update the view as follows:

<Window x:Class="ObjDataProvider_BindingMethodParameters.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:ObjDataProvider_BindingMethodParameters"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ObjectDataProvider ObjectType="{x:Type local:ExponentCalculator}"
MethodName="getResult" x:Key="expCalculator">
<ObjectDataProvider.MethodParameters>
<sys:Double>4</sys:Double>
<sys:Double>2</sys:Double>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>

<local:doubleStringConverter x:Key="conv" />

</Window.Resources>
<Grid>
<TextBox Height="30" HorizontalAlignment="Left" Margin="69,12,0,0"
Name="textBoxNumber" VerticalAlignment="Top" Width="422"
Text="{Binding Source={StaticResource expCalculator}, Path=MethodParameters[0], BindsDirectlyToSource=True, Mode=OneWayToSource, Converter={StaticResource conv}, UpdateSourceTrigger=PropertyChanged}" />
<Label Content="Number" Height="33" HorizontalAlignment="Left" Margin="6,10,0,0"
Name="label1" VerticalAlignment="Top" Width="57" />
<TextBox Height="30" HorizontalAlignment="Left" Margin="69,51,0,0" Name="textBoxPower"
VerticalAlignment="Top" Width="422"
Text="{Binding Source={StaticResource expCalculator}, Path=MethodParameters[1], BindsDirectlyToSource=True, Mode=OneWayToSource, Converter ={StaticResource conv}, UpdateSourceTrigger=PropertyChanged}" />
<Label Content="Power" Height="33" HorizontalAlignment="Left" Margin="6,49,0,0"
Name="label2" VerticalAlignment="Top" Width="57" />
<Label Content="Result" Height="33" HorizontalAlignment="Left" Margin="6,88,0,0"
Name="label3" VerticalAlignment="Top" Width="57" />
<TextBlock Height="31" HorizontalAlignment="Left" Margin="69,88,0,0" Name="textBlockResult"
Background="PaleTurquoise" VerticalAlignment="Top" Width="419" >
<TextBlock.Text>
<Binding Source="{StaticResource expCalculator}" />
</TextBlock.Text>
</TextBlock>
</Grid>
</Window>

As you can see we have instantiated the converter in the Resources section of the Window. We have assigned it the key conv. We are using the Converter instance for Binding with the Text property of the two text boxes. We have also update the UpdateSourceTrigger to PropertyChanged for both binding. This would keep updating the method parameters as we type in the two text boxes. The default value for this property is LostFocus for Text property of TextBox.

Now we run the application. This display should not be surprising for you. This is exponent ZERO on ZERO. We know that if we raise a number to zero exponent the result is always 1 no matter what the actual number really is.


If we update the Number and exponent as 3 and 2 respectively, the result is updated as 9 which is the expected result.



Download:

Wednesday, January 26, 2011

WPF - Performance Improvement for MVVM Applications - Part # 1

This is a series of posts about performance improvements of an MVVM based applications. You can find the other posts here:

- Part 2 : http://shujaatsiddiqi.blogspot.com/2011/02/wpf-performance-improvement-for-mvvm.html

- Part 3: http://shujaatsiddiqi.blogspot.com/2011/03/wpf-performance-improvement-for-mvvm.html

In this example we are discussing the various performance improvement for a WPF Binding developed using MVVM. This is for enhancing user experience by increasing the responsiveness of the system. MVVM based application is highly dependent upon the WPF Binding system. I think if we use certain features of Binding system then we can achieve this.
<Window x:Class="WpfApplication_ASync_Binding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication_ASync_Binding"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:MainWindowViewModel />
</Window.DataContext>
<Grid>
<TextBlock  Height="56" HorizontalAlignment="Left"
Margin="40,71,0,0" Name="label1" VerticalAlignment="Top"
Width="434" Background="Aquamarine" >
<TextBlock.Text>
<Binding Path="StudentName" StringFormat="testtt:{0}" />
</TextBlock.Text>
</TextBlock>
</Grid>
</Window>

We are not changing the code behind of the view so it should be as created by default. The view model:
namespace WpfApplication_ASync_Binding
{
using System.ComponentModel;

class MainWindowViewModel : INotifyPropertyChanged
{
private Student _student;
public MainWindowViewModel()
{
_student = new Student();
} 

private string _studentName;
public string StudentName
{
get
{
return _student.StudentName;
}
set
{
_student.StudentName = value;
OnPropertyChanged(StudentName);
}
} 

public event PropertyChangedEventHandler PropertyChanged; 

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

The view model is using _student as model. This is an instance of Student class. As you can see StudentName is just a proxy property for the model’s property named StudentName. The definition of Student is as follows:
namespace WpfApplication_ASync_Binding
{
class Student
{
public string StudentName { get; set; } 

public Student()
{
StudentName = "Muhammad";
}
}
}

Let’s run this application. The output should appear as follows:


Now let’s change this a bit. Let’s consider Student is using some complex logic for its property StudentName. It might be using a web service which might be slow. Now since we are using proxy property for binding this delay would slow down the binding and the form would become idle. Let’s create this scenarios by just introducing a delay using Thread.Sleep() as follows:
namespace WpfApplication_ASync_Binding
{
class Student
{
private string _studentName;
public string StudentName
{
get
{
//imaginary delay
Thread.Sleep(10000);
return _studentName;
}
set { _studentName = value; }
}

public Student()
{
StudentName = "Muhammad";
}
}
}

Now run the application. The same form would display but after a delay of atleast 10 seconds.

Basically when Binding system would access the getter for StudentName property in the DataContext. It would be delayed because the view model would be trying to get the Model’s property resulting in a delay of atleast 10 seconds (because of Thread.Sleep). So form instance is created. It assigns the DataContext as MainWindowViewModel in InitializeComponent. When it attempts to bind the Text property of TextBlock. It experiences this delay. So the delay is because of binding. If this binding becomes asynchronous then the performance could improve. You should be glad to learn that WPF Binding system supports making its binding asynchronous by providing IsAsync property in Binding markup extension. Let’s use this!

We update the view as follows:
<TextBlock.Text>
<Binding Path="StudentName" StringFormat="testtt:{0}" IsAsync="True" />
</TextBlock.Text>

Now run this. The form appears as follows:


This would be shown like this for atleast 10 seconds. During this time, it starts a ThreadPool thread on the background to get the Binding source. As soon as the source property becomes available, the binding updates the view as follows:


Well this is good but user sees nothing on the screen for atleast 10 seconds. We might want to show something else to the user until the data becomes available as a fallback mechanism. WPF binding system supports that too. You can achieve that by setting FallBackValue propery of Binding as follows:
<TextBlock.Text>
<Binding Path="StudentName" StringFormat="testtt:{0}"
IsAsync="True" FallbackValue="Test Fallback value" />   
</TextBlock.Text

Now run the application. The window is shown as follows:


This is shown like that for 10 seconds showing the Fallback value for Binding. You can see that StringFormat is not applied for FallbackValue. After 10 seconds, it updates itself as follows:


In order to have more sophisticated fallback mechanism, you might want to consider Priority Binding.

http://shujaatsiddiqi.blogspot.com/2010/09/wpf-priority-binding.html

The world is not simple. Let’s make it a little complex by updating the constructor of our model (Student) as follows:
public Student()
{
StudentName = "Muhammad";
Thread.Sleep(20000);
}

This is to simulate the 20 seconds further delay in Binding. Let’s run the application. For 20 seconds, nothing appears on the screen. After that the window appears with the fallback value. The fallback value remains on the view for 10 seconds. After that the view is updated with the finalized value for StudentName with applied StringFormat. Now the main question is why this window appears after 20 seconds when binding is asynchronous. Basically Binding.IsAsync just makes the Binding asynchronous. If there is a delay in the construction of DataContext, this would still be on the UI thread hence synchronous. The construction of DataContext (MainWindowViewModel) is causing this delay because of delay of instantiation of the Student (model) in the constructor of view model [Thread.Sleep(20000)].

In order to improve this behavior we can update the way DataContext is constructed. We can construct the object using ObjectDataProvider. This is to utilize the asynchronous instantiation feature of ObjectDataProvider. We can cause asynchronous construction by setting IsAsynchronous for ObjectDataProvider. Let’s update the definition of the section of XAML for view where we are assigning DataContext as follows:
<Window.DataContext>
<ObjectDataProvider ObjectType="{x:Type local:MainWindowViewModel}" IsAsynchronous="True"  />
</Window.DataContext>

Now run the application. As we run the application there is no delay and the following screen appears:


This is maintained for 30 seconds. The 20 seconds is for the construction of DataContext (causing construction of model) and the other 10 seconds is for the delay in the getter for StudentName property from DataContext. Basically the Fallback value is maintained until the value is available no matter the delay is called by the DataContext construction or the available of its property.

10 + 20 = 30 seconds

Eventually the window is updated as follows:


Download: