Silverlight MVVM Light - 从xaml设置控件依赖项属性值

时间:2011-02-24 18:29:22

标签: silverlight xaml data-binding mvvm-light

我正在使用MVVM Light和SL4。我的视图正在通过定位器解析他们的视图模型,一切都很好。

我的问题是我的一个视图有一个我需要在另一个视图中设置的属性。

即。 HomeView可以有许多组件视图实例。但在该主视图上,我想在组件视图上设置属性。我已经尝试将依赖属性添加到视图后面的代码 - 然后我可以从HomeView设置,但我的组件视图模型不会提取它。

这可能吗?

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>

1 个答案:

答案 0 :(得分:0)

我想我可以帮助你一段时间前,我回答了类似的问题:

Silverlight: How to bind to parent view's DataContext?

我的示例中的子视图包含一个依赖项属性,它在父视图中设置了它的值。子视图使用与ElementName =“this”

的绑定绑定到该依赖项属性