Lets say I have an ItemsControl in a Canvas.
Each Item will have its own position, but I want all items to share that same width. So if the user changes it in one place, all items get updated. What is the cleanest way to do this?
Right now I see 2 solutions.
- Whenever the settings change, I update the width property for each item. The disadvantage is, that this takes more resources than necessary, but now the view for each item simply binds to this property.
- I add a Width property to the ViewModel that is bound to the Control containing the items. I give the ItemsControl a name (e.g. "MyItemsContainer").
Now each item can get to it via:
{Binding ElementName=MyItemsContainer, Path=DataContext.Width}
The disadvantages with the second solution are the added dependencies. First of all there has to be an ItemsControl by that name (which makes it impossible to use the item in a differently named ItemsControl) and the ItemsControl's DataContext needs to have a Width property.
I would be interested in finding alternative solutions or what experiences people 开发者_JAVA百科have made with either solution.
If you eliminate redundancy by declaring the properties at the highest possible level (ie. your parent view model), you can either:
- Have a child view model for each item in your
ItemsControl
. This child view model can also expose the same properties, but forward all access to the parent view model. Note that this requires the child view models to also forward property change events from the parent view model. You can use Truss to make this much easier by binding the child's property to the parent's. - Have your view use a
Binding
with aRelativeSource
instead ofElementName
so you at least eliminate the dependency on a specific namedItemsControl
.
精彩评论