【问题标题】:Silverlight MVVM Light - Setting a control dependency property value from xamlSilverlight MVVM Light - 从 xaml 设置控件依赖属性值
【发布时间】:2011-02-24 18:29:22
【问题描述】:

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

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

即一个 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>

【问题讨论】:

    标签: silverlight xaml data-binding mvvm-light


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2012-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-26
      • 1970-01-01
      • 2016-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多