繁体   English   中英

直接公开用户控件的子属性作为用户控件的属性

[英]Expose child properties of user control directly as property of user control

在不破坏MVVM的情况下,是否有办法在用户控件中公开子控件的某些属性,以便使用它的窗口或其他用户控件可以直接访问这些属性?

例如,我有一个用户控件,该控件的listview设置有gridviewcolumns,标头,并绑定到视图模型。 但是用户控件中的列表视图具有选定的项目属性,因此我想向主机公开而不需要执行诸如usercontrol.customListView.property之类的操作。 还是那应该怎么做? 我只想去usercontrol.property,省略customListView。 也许我应该在后面的用户控件代码中创建属性,该属性返回我想直接附加到用户控件的列表视图控件属性?

我觉得后一种选择并没有真正破坏MVVM,因为它们公开给主机与之交互,与视图本身并没有真正的关系。 任何建议将不胜感激。

编辑:实际上,我真的很想直接在不是ListViewItem或对象的用户控件上拥有SelectedItem属性,但实际上包含的数据类型确实如下所示:

public MyDataType SelectedItem {
    get {
        return customListView.SelectedItem as MyDataType;
    }
}

在MVVM中允许吗? 因为我看不到如何在ViewModel中使用它,所以似乎必须在后面的部分类代码中。

当您要将重复的内容放入UserControl时,这是非常常见的任务。 最简单的方法是不为该UserControl创建专门的ViewModel,而是进行自定义控件 (为简便起见,使用UserControl进行构建)。 最终结果可能看起来像这样

<UserControl x:Class="SomeNamespace.SomeUserControl" ...>
    ...
    <TextBlock Text="{Binding Text, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}" ...>
</UserControl>

public partial class SomeUserControl : UserControl
{
    // simple dependency property to bind to
    public string Text
    {
        get { return (string)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }
    public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register("Text", typeof(string), typeof(SomeUserControl), new PropertyMetadata());

    // has some complicated logic
    public double Value
    {
        get { return (double)GetValue(ValueProperty); }
        set { SetValue(ValueProperty, value); }
    }
    public static readonly DependencyProperty ValueProperty =
        DependencyProperty.Register("Value", typeof(double), typeof(SomeUserControl),
        new PropertyMetadata((d, a) => ((SomeUserControl)d).ValueChanged()));
    private void ValueChanged()
    {
        ... // do something complicated here
            // e.g. create complicated dynamic animation
    }

    ...
}

用法在包含窗口中看起来像这样

<l:SomeUserControl Text="Text" Value="{Binding SomeValue}" ... />

如您所见, SomeValue绑定到Value并且没有违反MVVM。

当然,如果视图逻辑复杂或需要太多绑定,并且允许ViewModels直接通信(通过属性/方法)比较容易,则可以创建适当的ViewModel

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM