Binding nested UserControls to properties exposed in the ViewModel
I have a UserControl that has an image on it. It has it's Visibility property bound to a property (named "On") on the ViewModel (which raises a Property开发者_JAVA技巧Changed event). Now I'd like to create another UserControl which contains a few of these UserControls. It will have its own ViewModel which will expose another set of properties that should effect these image UserControls.
I could just use FindName and explicitly grab their view model and set the On property, but I was wondering if there was a way to handle this through binding, ex.
<local:MyImageView x:Name="MyImage1" On="{Binding Image1On}" />
Where Image1On would be another property on the second UserControl's ViewModel.
The way I would usually handle this is by having the new view model you are talking about contain instances of your original view models with the "On" property. (Whether it is a direct property or a collection of them depends on the situation) Then instead of dealing with the UI elements, you are just dealing with the properties of your view models.
For example: "Room" view model contains a Collection of "Light" view models.
public class RoomViewModel
{
LightViewModel frontLights
{
//implementation
}
LightViewModel rearLights
{
//implementation
}
// Create a ICommand Implementation around this
public void ToggleFrontLights(bool turnLightsOn)
{
frontLights.On = turnLightsOn;
}}
精彩评论