从用户控件更改Windows内容控件-WPF

时间:2018-11-10 18:30:07

标签: c# wpf xaml viewmodel

在我的项目中,我有一个名为AccountWindow.xaml的窗口,该窗口具有一个ContentControl来显示两个UserControl。

AccountWindow

<Window>
    <Window.Resources>
        <!-- Login User Control Template -->
        <DataTemplate x:Name="LoginUserControl" DataType="{x:Type ViewModels:LoginViewModel}">
            <AccountViews:LoginUserControl DataContext="{Binding}"/>
        </DataTemplate>

        <!-- Registration User Control Template -->
        <DataTemplate x:Name="RegistrationUserControl" DataType="{x:Type ViewModels:RegistrationViewModel}">
            <AccountViews:RegistrationUserControl DataContext="{Binding}" />
        </DataTemplate>
    </Window.Resources>

    <Grid>
        <!-- ContentControl that displays the two User Controls -->
        <ContentControl Content="{Binding}" />
    </Grid>
</Window>

然后我有两个用户控件,分别称为LoginUserControl和RegistrationUserControl

登录用户控件

<Grid Background="Pink">
        <Button Content="Switch To Register View" Command="{Binding SwitchToReg}" Margin="100" />
    </Grid>

注册用户控件

<Grid Background="Orange">
    <Button Content="Press Me" Command="{Binding PressMe}" Margin="100" />
</Grid>

登录用户控件和注册用户控件都有自己的ViewModel,其中的RelayCommand绑定到代码中所示的按钮上。

登录视图模型

public class LoginViewModel
    {
        public RelayCommand SwitchToReg
        {
            get
            {
                return new RelayCommand(param =>
                {
                    Console.WriteLine("Switch To Reg");
                    // Somehow change the content control in the AccountWindow to show the RegistrationDataTemplate???
                });
            }
        }
    }

问题

当用户按下UserControls中的按钮之一时,我希望能够在AccountWindow中更改ContentControl的内容。例如,当用户按下登录用户控件中名为“切换到注册视图”的按钮时,它将执行Command SwitchToReg并将内容控件更改为RegistrationUserControl及其ViewModel。这怎么可能?

2 个答案:

答案 0 :(得分:0)

要实现这一点,您在构造AccountWindow时需要将其传递给UserControl,然后Command可以使用提供的引用来更新ContentControl。

这是引入耦合的一种方法,可以更好地避免这种耦合,因此我建议考虑考虑AccountWindow的设计。我将使用网格行将ContentControl区域与按钮分开,这将更改UserControl。

Example window

在上面的窗口中,蓝色区域是我托管ContentControl的位置,红色区域是AccountWindow的一部分。

这样,切换ContentControl的行为完全由AccountWindow处理。

答案 1 :(得分:-1)

您可以创建属性并将其附加到控件。 或者,您可以创建另一个用户控件并使之可见,或者不受您创建的属性的控制。

相关问题