In my application I am binding several text boxes to properties. So in c# I have:
public class MyUserControl : UserControl, INotifyPropertyChanged
{
decimal _Price;
public decimal Price
{
get { return _Price; }
set
{
_Price = value;
OnPropertyChanged("Price");
}
}
// implement interface
public event PropertyChangedEventHandler PropertyChanged = delegate { };
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
// etc
and on xaml I have:
<TextBox Name="txtPrice" DataContext="{Binding}" Text="{Binding Price, UpdateSourceTrigger=PropertyChanged, StringFormat=c}"></TextBox>
then If in my code behind I set the Price = 12.22 for example it will display $12.22 in the textbox.
Now because I am using this behavior very often I want to create a class that will create the property binded to the textbox for me. So my class looks like:
public class ControlBind<T> : INotifyPropertyChanged
{
protected T _Value;
public T Value
{
get { return _Value; }
set
{
_Value = value;
OnPropertyChanged("Value");
}
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public ControlBind(Control control, System.Windows.DependencyProperty controlPropertyToBind)
{
Binding b = new Binding("Value")
{
Source = this
};
b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
control.SetBinding(controlPropertyToBind, b);
}
}
then I will be able to use that class and create the same behavior by doing:
// txtPrice is a textbox defined in xaml
ControlBind<decimal> Price = new ControlBind<decimal>(txtPrice, TextBox.TextProperty);
Price.Value = 45; // update textbox value to "45"
but now I don’t know how to do the string format. When I use the class, the textbox prints 45 and I want it to print $45
So in other words how can I achieve xaml binding {Binding Price, StringFormat=c} in code behind
Not tested, but I think: