Introduction
This article allows you to databind calculated/computed properties without the need to worry about creating converters or custom value-changed code-behind that is hard to maintain.
Background
In the example presented, I am using a simple Expense
object that has a few fields: FirstName
, LastName
, Utility
, CreditCard
, Other
. The idea is to use these fields in a way that changes to any of the fields updates any computed custom fields that we may have such as FullName
or TotalExpenses
.
There are multiple places where you can place your custom property declarations. Either server side in a .shared.cs file or client side by creating a partial class extension.
I picked server side to keep the business logic in one place but that is not the point I am trying to make.
The main idea behind this article is to allow object based data binding that we can achieve by adding some hooks on the client side.
Assuming that we added the following code to the server side ServerSideEvents.shared.cs file:
namespace SilverlightDatabinding.Web.DataModel
{
public partial class Expense
{
public string Name
{
get
{
return ((FirstName != null ? FirstName : "") + " " +
(LastName != null ? LastName : "")).Trim();
}
}
public decimal TotalExpenses
{
get
{
return (Utility.HasValue ? Utility.Value : 0M) + (CreditCard.HasValue ?
CreditCard.Value : 0M) + (Other.HasValue ? Other.Value : 0M);
}
}
}
}
We can now add another client side partial class externsion CustomPropertiesExtension.cs:
namespace SilverlightDatabinding.Web.DataModel
{
public partial class Expense
{
partial void OnFirstNameChanged()
{
this.RaisePropertyChanged("Name");
}
partial void OnLastNameChanged()
{
this.RaisePropertyChanged("Name");
}
partial void OnUtilityChanged()
{
this.RaisePropertyChanged("TotalExpenses");
}
partial void OnCreditCardChanged()
{
this.RaisePropertyChanged("TotalExpenses");
}
partial void OnOtherChanged()
{
this.RaisePropertyChanged("TotalExpenses");
}
}
}
Now in XAML, we can bind to the custom property directly without worrying about whether it will get updated properly on the UI or not.
<textblock verticalalignment="Center" text="{Binding TotalExpenses}" width="200"
fontweight="Black" grid.column="1" grid.row="6" horizontalalignment="Left" margin="5,5,5,5" />
Hope you find this useful. My first attempt to share some of my experiences.