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(&quot;CurrentVM&quot;);
    }
}

Quribe
  • 25
  • 6
  • В таких случаю используют DataTemplate для ContentControl.ContentTemplate и DataTemplateSelector для выбора нужного DataTemplate. –  Jan 11 '23 at 04:57
  • Реализацию свойства CurrentVM покажите. Где INPC? https://ru.stackoverflow.com/a/1266479/373567 – aepot Jan 11 '23 at 05:50
  • @aepot, Добавил – Quribe Jan 11 '23 at 05:54
  • Выглядит нормально. – aepot Jan 11 '23 at 05:56

1 Answers1

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.

wchistow
  • 3,697
  • 6
  • 13
  • 32
Quribe
  • 25
  • 6