I got the following code for my object (short version) :
public class PluginClass
{
public int MyInt
{
get;
set;
}
public PluginClass()
{
Random random = new Random();
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed += (sender, e) =>
{
MyInt = random.Next(0, 100);
}
}
}
Then I’m creating another class with an int as a DependencyProperty. Here is the code (simplified version too)
public class MyClass : FrameworkElement
{
public int Value
{
get
{
return GetValue(ValueProperty);
}
set
{
SetValue(ValueProperty, value);
}
}
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(int), typeof(MyClass ), new PropertyMetadata(0));
public MyClass(object source, string propertyName)
{
var b = new System.Windows.Data.Binding();
b.Source = source;
b.Path = new PropertyPath(propertyName);
b.Mode = System.Windows.Data.BindingMode.TwoWay;
SetBinding(ValueProperty, b);
}
}
Finally I’m creating an instance of PluginClass and I’d like to bind my “MyInt” value to the int of MyClass. Here is what I got (simplified version too)
PluginClass pc = new PluginClass();
MyClass mc = new MyClass(pc, "MyInt");
No compilation problem but the binding is not effective.
To summarise, I don’t know if I theorically have to got :
binding.Source = PluginClass.MyInt;
binding.Path = new PropertyPath("???"); // don't know what to "ask"
or
binding.Source = PluginClass;
binding.Path = new PropertyPath("MyInt");
I think the 2nd way is the good one but I don’t know why it doesn’t work 🙁
Any help will be very appreciated !
Your
PluginClassshould implement INotifyPropertyChanged. For now, the binding has no idea the value ofMyInthas changed.Implementing INPC will allow your class to inform the binding when the value changes (you will have to raise
PropertyChangedin your set function ofMyInt).