簡體   English   中英

WPF:在ViewModel上使用稍微不同的調用來重用控件嗎?

[英]WPF: Reusing control with slightly different call on ViewModel?

我有一個控件ActionRequiredControl.xaml,其中包含一個帶有枚舉列表的組合框。 此控件具有ActionRequiredViewModel作為其DataContext,並且以下調用用於填充組合框:

    public IEnumerable<ActionType> Actions
    {
        get
        {
            return Enum.GetValues(typeof(ActionType)).Cast<ActionType>();
        }
    }

並且組合框如下。

   <StackPanel Orientation="Vertical">
   <Label>Action:</Label>
   <ComboBox Width="170" MinHeight="45"  Margin="5,0,5,5" Padding="5" 
             SelectedItem="{Binding Action, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
             ItemsSource="{Binding Actions, Mode=OneTime}" 
             VerticalContentAlignment="Center" IsEnabled="{Binding IsUsed}"/>
   </StackPanel>

當前在兩個地方使用了此控件(除了組合框以外,還有更多其他用途)-但是,我想在第三個地方重用它,只有“動作”函數返回的不同列表。

最好的方法是什么? 我唯一想到的就是創建一個從ActionRequiredViewModel繼承並覆蓋Actions方法的新類。

最簡單的解決方案是我在問題中指出的解決方案-我創建了一個繼承自ActionRequiredViewModel的新類,並覆蓋了“ Actions”方法以返回不同的枚舉列表。

是的,創建其他ViewModel是最簡單的解決方案。 不久前我處於類似的情況,我的第一個實現(使用MVVM light)是使用兩個VM,並在ViewModelLocator中注冊這兩個VM,並為每個VM提供一個屬性:

SimpleIoc.Default.Register<ViewModel1>();
SimpleIoc.Default.Register<ViewModel2>();

public ViewModel ViewModel1Instance
{
    get
    {
        return ServiceLocator.Current.GetInstance<ViewModel1>();
    }
}

public ViewModel ViewModel2Instance
{
    get
    {
       return ServiceLocator.Current.GetInstance<ViewModel2>();
    }
}

然后在XAML中:

<local:MyUserControl DataContext="{Binding ViewModel1Instance, 
    Source={StaticResource Locator}}" ...

但是,為更加靈活起見,我稍后將其替換為另一個解決方案,該解決方案提供了更好的自定義。

我滿足了您的要求,並提出了以下解決方案:

在用戶控件后面的代碼中創建依賴項屬性作為代理:

public static readonly DependencyProperty ComboBoxItemsProperty =
            DependencyProperty.Register("ComboBoxItems",
            typeof(IEnumerable<object>), typeof(TestUserControl));


public IEnumerable<object> ComboBoxItems
{
    get
    {
        return (IEnumerable<object>)GetValue(ComboBoxItemsProperty);
    }
    set
    {
        SetValue(ComboBoxItemsProperty, value);
    }
}

在用戶控件的XAML中:

...ItemsSource="{Binding ComboBoxItems, Mode=OneWay, RelativeSource=
    {RelativeSource AncestorType={x:Type UserControl}}}"...

在主視圖模型中:

public IEnumerable<object> Items
{
    get
    {
        return Enum.GetValues(typeof(ActionType)).Cast<object>();
    }
 }

在主要的XAML中:

<local:TestUserControl ComboBoxItems="{Binding DataContext.Items, 
    Mode=OneTime, 
    RelativeSource={RelativeSource AncestorType={x:Type Window}}}">
</local:TestUserControl>

這對我有用,但是使用object而不是自定義類型並不是最優雅的解決方案。

PS:這是我關於SO的第一個答案,(而且我還沒有問題……)。

由於我多年來一直將SO用作提示和技巧的主要來源,所以我認為我可以嘗試回饋一些東西...

當然,我承認:嘗試回答並不是學習新主題的最糟糕方法(而且WPF對我而言還很陌生,所以請不要怪我回答不佳:-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM