Silverlight MVVM Light - Setting a control dependency property value from xaml
I am using MVVM Light with SL4. My View's are resolving their View Model via the locator, all is fine.
My problem is that one of my views has a property that I need to set in another view.
i.e. a HomeView can have many instances of a component view. But on that home view I want to set the property on the component view. I've tried adding a dependency property to the code behind of the view - which I can then set from HomeView, but my component view model does not pick it up.
Is this possible to do?
ComponentControl.cs
public enum CustomStyle
{开发者_运维技巧
Active,
Draft,
Completed
}
public class ComponentControl : Control
{
public ComponentControl()
{
DefaultStyleKey = typeof (ComponentControl);
}
public CustomStyle CustomType
{
get { return (CustomStyle)GetValue(CustomTypeProperty); }
set { SetValue(CustomTypeProperty, value); }
}
public static readonly DependencyProperty CustomTypeProperty =
DependencyProperty.Register("CustomType",
typeof(CustomStyle),
typeof(ComponentControl), null);
}
ComponentViewModel.cs
public CustomStyle CustomType
{
get { return _customType; }
set
{
if (value == _customType)
return;
_customType = value;
base.RaisePropertyChanged("CustomType");
}
}
private CustomStyle _customType;
ComponentView.xaml.cs
public static readonly DependencyProperty CustomTypeProperty =
DependencyProperty.Register("CustomType",
typeof(CustomStyle),
typeof(ComponentView), null);
public CustomStyle CustomType
{
get { return (CustomStyle)GetValue(CustomTypeProperty); }
set { SetValue(CustomTypeProperty, value); }
}
ComponentView.xaml
<Grid>
<common:ComponentControl
DataContext="{Binding Path=WorkflowList, Mode=OneWay}"
CustomType="{Binding Path=CustomType, Mode=TwoWay,
ElementName=root}" />
</Grid>
HomeView.xaml
<Grid x:Name="LayoutRoot">
<common:HomeControl x:Name="homeControl">
<common:HomeControl.ActiveContent>
<local:ComponentView x:Name="active" CustomType="Active" />
</common:HomeControl.ActiveContent>
<common:HomeControl.DraftContent>
<local:ComponentView x:Name="draft" CustomType="Draft" />
</common:HomeControl.DraftContent>
<common:HomeControl.CompletedContent>
<local:ComponentView x:Name="completed" CustomType="Completed" />
</common:HomeControl.CompletedContent>
</common:HomeControl>
</Grid>
I think I can help you a bit, a while ago I answered a similar question :
Silverlight: How to bind to parent view's DataContext?
The child view in my example contains a dependency property, which has it's value set in the parent view. The child view binds to that dependency property using a binding with ElementName="this"
精彩评论