C# 将Windows内容控件从用户控件更改为WPF

C# 将Windows内容控件从用户控件更改为WPF,c#,wpf,xaml,viewmodel,C#,Wpf,Xaml,Viewmodel,在我的项目中,我有一个名为AccountWindow.xaml的窗口,它有一个ContentControl来显示两个UserControl 账户窗口 <Window> <Window.Resources> <!-- Login User Control Template --> <DataTemplate x:Name="LoginUserControl" DataType="{x:Type ViewModels:

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

账户窗口

<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>
问题


我希望当用户按下UserControls中的一个按钮时,能够在AccountWindow中更改ContentControl的内容。例如,当用户按下登录用户控件中名为“Switch To Register View”的按钮时,它会执行命令SwitchToReg并将内容控件更改为RegistrationUserControl及其ViewModel。这怎么可能呢?

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

要实现这一点,您需要在构建时将AccountWindow的引用传递到UserControl中,然后您的命令可以使用您提供的引用更新ContentControl

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

在上面的窗口中,蓝色区域是ContentControl的宿主,红色区域是AccountWindow的一部分


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

感谢您的帮助回答。在发布我的问题后,我意识到了您所描述的问题。我现在已经实现了你的建议。
<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>
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???
                });
            }
        }
    }