簡體   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