1

Есть окно, в котором есть шапка с кнопками для переключения различных вкладок. Этими вкладками являются несколько UserControl. Окно имеет ContentControl после шапки, в котором я хочу располагать свои UserControl. Предполагается, что при нажатии определённой кнопки должен применяться соответствующий UserContent. Пожалуйста, подскажите, как я могу это реализовать?

Кнопка:

 <Button Width="200px" Command="{Binding AccomplishedPurchasesButton}">
                <Button.Background>
                    <SolidColorBrush Opacity="1"/>
                </Button.Background>
                <Label>
                    <TextBlock Text="Совершённые покупки"
                               TextWrapping="Wrap"
                               FontSize="28"
                               TextAlignment="Center"
                               LineStackingStrategy="BlockLineHeight"
                               LineHeight="30"
                    />
                </Label>
            </Button>

ContentControl:

<ContentControl x:Name="contentControl" Grid.Row="3" Content="{Binding CurrentVM}"/>

RelayCommand для кнопки:

private RelayCommand accomplishedPurchasesButton;
    public RelayCommand AccomplishedPurchasesButton
    {
        get
        {
            return accomplishedPurchasesButton ??
              (accomplishedPurchasesButton = new RelayCommand(obj =>
              {
                  CurrentVM = new PurchasePlan_UC_VM();
              }));
        }
    }

Я пытался применить разные способы, которые я смог найти, но так ничего и не смог, так как мне не хватает понимания и опыта работы с WPF и MVVM. Буду очень благодарен, если бы вы могли объяснить, что к чему. Скажите, если нужна дополнительная информация.

Реализация свойства CurrentVM

Base_VM currentVM;

    public Base_VM CurrentVM
    {
        get { return currentVM; }
        set
        {
            currentVM = value; 
            OnPropertyChanged("CurrentVM");
        }
    }
4
  • В таких случаю используют DataTemplate для ContentControl.ContentTemplate и DataTemplateSelector для выбора нужного DataTemplate.
    – user532595
    11 янв в 4:57
  • Реализацию свойства CurrentVM покажите. Где INPC? ru.stackoverflow.com/a/1266479/373567
    – aepot
    11 янв в 5:50
  • @aepot, Добавил
    – Quribe
    11 янв в 5:54
  • Выглядит нормально.
    – aepot
    11 янв в 5:56

1 ответ 1

0

Проблема решается с помощью использования DataTemplate.

В Window.Resources я разместил необходимые мне DataTemplates:

<Window.Resources>
    <DataTemplate DataType="{x:Type VM:AccomplishedPurchases_UC_VM}">
        <V:AccomplishedPurchases_UC/>
    </DataTemplate>
    <DataTemplate DataType="{x:Type VM:PurchasePlan_UC_VM}">
        <V:PurchasePlan_UC/>
    </DataTemplate>
</Window.Resources>

Обе мои кнопки выглядят так:

<Button Width="150px" Command="{Binding PurchasePlanButton}" >
    <Button.Background>
        <SolidColorBrush Opacity="1"/>
    </Button.Background>
    <Label>
        <TextBlock Text="Purchase Plan"
                TextWrapping="Wrap"
                FontSize="28"
                TextAlignment="Center"
                LineStackingStrategy="BlockLineHeight"
                LineHeight="30"
        />
    </Label>
</Button>

И ContentControl имеет следующую привязку контента:

<ContentControl x:Name="contentControl" Grid.Row="3" Content="{Binding CurrentVM}"/>

MainWindow ViewModel:

Base_VM currentVM;

public Base_VM CurrentVM
{
    get { return currentVM; }
    set
    {
        currentVM = value; 
        OnPropertyChanged("CurrentVM");
    }
}

private RelayCommand accomplishedPurchasesButton;
public RelayCommand AccomplishedPurchasesButton
{
    get
    {
        return accomplishedPurchasesButton ??
          (accomplishedPurchasesButton = new RelayCommand(obj =>
          {
              CurrentVM = new AccomplishedPurchases_UC_VM();
          }));
    }
}

private RelayCommand purchasePlanButton;
public RelayCommand PurchasePlanButton
{
    get
    {
        return purchasePlanButton ??
          (purchasePlanButton = new RelayCommand(obj =>
          {
              CurrentVM = new PurchasePlan_UC_VM();
          }));
    }
}

Base_VM реализует INotifyPropertyChanged.

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.