'How to create a property binding in C#?
I am looking for a generic solution to specify relationships between properties so that if a dependency of a property changes, the value of the property is automatically updated.
I am aware that this is not an odd idea and e.g. there is a solution in Qt, but I didn't find a similar one in the .NET Framework.
I want to achieve something like this:
public class Rectangle
{
public IProperty<int> Height;
public IProperty<int> Width;
public IProperty<int> Area;
public Rectangle(int height, int width)
{
Height = new Property<int>(height);
Width = new Property<int>(width);
Area = new Property<int>(() => Height.Value * Width.Value);
}
}
Which in use could be like this:
var rectangle = new Rectangle(10, 20); // rectangle.Area.Value == 200
rectangle.Width.Value = 5; // rectangle.Area.Value == 50
The IProperty interface might look something like this:
public interface IProperty<T>
{
T Value { get; set; }
event EventHandler ValueChanged;
}
My idea was that when the Area property is initialized, it would have to subscribe to (and somehow unsubscribe from) the ValueChanged event of all IProperty objects in the lambda expression. Later, if an IProperty object raises a ValueChanged event, the Area property would evaluate the lambda expression.
- Is all this possible in the .NET Framework? If so, how can this be achieved?
- What if the lambda expression includes a collection of
IPropertyobjects?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
