Binding to a Dependency Property is easy in code-behind. You just create a new System.Windows.Data.Binding
object, and then call the target dependency object's SetBinding
method.
But how do you do this when the property which we're binding is a CLR property and you can't provide a DependencyProperty
argument to SetBinding
? Is there a way to use a CLR property as a binding target?
EDIT: The object implements INotifyPropertyChanged
, if that's relevant.
Common Language Runtime (CLR) properties can be used to define effect parameters that don't respond to runtime property changes. This article demonstrates using CLR properties to pass parameters to an effect.
Instead of calling SetBinding, you can use the SetBinding static method of the BindingOperations class. The following example, calls BindingOperations. SetBinding instead of FrameworkElement. SetBinding to bind myText to myDataProperty .
Data binding is the process that couples two data sources together and synchronizes them. With data binding, a change to an element in a data set automatically updates in the bound data set.
Binding targets MUST be dependency properties! That's the only requirement for databinding to work!
Read more here:
For this to be possible, the property must be one for which you are writing the setter (so, not a property defined in code you can't change).
Then the solution is Implement Property Change Notification.
Sample code from above link:
using System.ComponentModel;
namespace SDKSample
{
// This class implements INotifyPropertyChanged
// to support one-way and two-way bindings
// (such that the UI element updates when the source
// has been changed dynamically)
public class Person : INotifyPropertyChanged
{
private string name;
// Declare the event
public event PropertyChangedEventHandler PropertyChanged;
public Person()
{
}
public Person(string value)
{
this.name = value;
}
public string PersonName
{
get { return name; }
set
{
name = value;
// Call OnPropertyChanged whenever the property is updated
OnPropertyChanged("PersonName");
}
}
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
}
In that implementation, each property setter must call
OnPropertyChanged("YourPropertyName");
Or for a slightly different implementation, that avoids having to re-enter the property name as a string parameter, see my answer here.
There, I also mention Fody/PropertyChanged, TinyMvvm, and MvvmCross as libraries that can help implement this pattern.
(I'm working in Xamarin Forms, but I think those are all useable from WPF as well; they are based on System.ComponentModel namespace.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With