Change the content of the grid row

时间:2015-11-12 11:23:43

标签: c# wpf xaml

I apologize if the question is easily answerable, but I am new to WPF.

I have a grid with 2 rows. First row will contain menu, and the second row has its content set in response to the menu item click.

For simplicity, let us take I have 2 menu items and 2 user controls.

Here is the example scenario:

At the beginning of the program, only menu is shown and the second grid row is empty.

User chooses first menu item -> second grid row should now contain first user control.

Now user chooses second menu item, so second row should contain second user control (while the previous content is deleted).

QUESTION:

What is the correct way of achieving this?

WHAT HAVE I TRIED SO FAR:

I have placed ContentControl in the second grid row, and am changing its Content on menu item click (below is the small code example).

XAML:

<Window x:Class="ZonaA.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:testUserControl="clr-namespace:ZonaA"
    Title="Zona A" 
    Height="350" Width="525" 
    WindowStartupLocation="CenterScreen">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Menu Grid.Row="0">
        <MenuItem Header="First user control" Click="C1" />
        <MenuItem Header="Second user control" Click=C2" />    
    </Menu>
    <ContentControl Name="windowContent" Content="" HorizontalAlignment="Stretch" Grid.Row="1" VerticalAlignment="Stretch"/>
</Grid>

Code behind:

private void C1(object sender, RoutedEventArgs e)
    {
        windowContent.Content = new myUserControl1();
    }

    private void C2(object sender, RoutedEventArgs e)
    {
        windowContent.Content = new myUserControl2();
    }

2 个答案:

答案 0 :(得分:0)

你可以使用Frame我认为这个工作也是如此here是一个视频,他使用框架来切换内容,而你只是在第一页中没有内容。希望它可以帮到你

答案 1 :(得分:0)

我认为解决问题的最佳方法是使用InteractionTriggers,这是一个例子。

首先,如果您决定使用此功能,则需要在项目中添加以下引用:

<强> System.Windows.Interactivity

<强> Microsoft.Expression.Interactions

这样做,是时候在XAML中声明它们以便使用它:

    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
    xmlns:ie="http://schemas.microsoft.com/expression/2010/interactions"

现在,如果这样说,你可以做所有你想要做的事情,而不需要在代码隐藏上写一行,如果你遵循MVVM模式就很好,这就像你的MenuItem一样:

<MenuItem Header="First user control">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="Click">
                    <ie:ChangePropertyAction TargetName="windowContent" PropertyName="Visibility" Value="Hidden"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
</MenuItem>

基本上你&#34;分配&#34;点击事件,并在事件被触发时执行某些操作,在我们的例子中,我们将执行一个名为ChangePropertyAction的操作,该操作将更改PropertyName =&#34; Visibility&#34;控制&#34; windowContent&#34; (需要定义控件名称)为值&#34; Hidden&#34;。

您只需要根据您的情况调整此示例,您必须在XAML上声明两个usersControl以更改其属性。