Consider a scenario where you want to add button to a grid in Code.
We have three classes
Button has to be put in 3rd grow and 2nd column of grid. Let us have interface IRowAndColumn
If we implement this interface in button we can write in main like this.
But suppose we want to add button to dock panel, you don't need rows and column properties. It is specific for grids and this turns into a bad design.
Can we implement the same in Grid. But how can we set the rows and column for the button ?
The grid structure look like this .
Now button might have rows, column properties as well as Dock properties. For that reason we can define the collection in UIElements.
And then we will have methods to set, get and clear the collection. In the below code we have taken dictionary so that property is unique.
The UIElement class looks like this.
Add caption |
Add caption |
Now in main, our code looks like this.
This looks very simple and property of parent control can be extended to the child. This property is nothing but attached properties.
In WPF every control is an DependencyObject. Now replace the UIElement with DependencyProperty. You get the attached property implementation.
No comments:
Post a Comment