Доступ к кнопке, созданной на странице вложенного xaml, из родительской оболочки xaml

Я работаю с приложением SplitView и создал оболочку, в которой размещаются подстраницы. Что я хотел бы сделать, так это иметь кнопку на подстранице, которая при нажатии может управлять видимостью объектов, изначально инициированных или созданных в XAML оболочки. Но я не уверен, как вызвать класс или фрейм, необходимые для изменения атрибутов в SplitView.

Моя иерархия выглядит следующим образом: «Оболочка» > «Папка страниц» > «Подстраницы».

Вот фрагмент из моего Shell.xaml Имейте в виду, что это только часть, содержащаяся в SplitView

<SplitView.Pane>
        <StackPanel x:Name="SplitViewPanePanel">
            <RadioButton x:Name="BackRadioButton" Click="BackRadioButton_Click" Style="{StaticResource NavRadioButtonStyle}" Tag="&#xE112;" Background="Gray" Content="Back" GroupName="Back"/>
            <RadioButton x:Name="HamburgerRadioButton" 
                         Click="HamburgerRadioButton_Click" 
                         Style="{StaticResource NavRadioButtonStyle}" 
                         Tag="&#xE700;"
                         Content="Menu" />

            <RadioButton x:Name="HomeRadioButton" Click="HomeRadioButton_Click" Style="{StaticResource NavRadioButtonStyle}" Tag="&#xE80F;" Content="Home" GroupName="Navigation"/>
            <RadioButton x:Name="TARadioButton" Click="MTRadioButton_Click" Style="{StaticResource NavRadioButtonStyle}" Tag="&#xE179;" Content="Team Assignments" GroupName="Navigation"/>
            <RadioButton x:Name="ASRRadioButton" Click="ASRRadioButton_Click" Style="{StaticResource NavRadioButtonStyle}" Tag="&#xE13C;" Content="Assignment Switch Requests" GroupName="Navigation"/>
            <RadioButton x:Name="MTRadioButton" Click="MTRadioButton_Click" Style="{StaticResource NavRadioButtonStyle}" Tag="&#xE15E;" Content="Management Tools" GroupName="Navigation"/>
        </StackPanel>
</SplitView.Pane>

Ниже приведен код моей «Домашней» страницы в папке «Страницы».

using Team_Management_Hub;
using Team_Management_Hub.Pages;

namespace Team_Management_Hub.Pages
{
    public sealed partial class Home : Page
    {
        public Home()
        {
            this.InitializeComponent();
        }

        private void TestButton_Click(object sender, RoutedEventArgs e)
        {
            //Here is the button I want to be able to click to alter the visibility of the MTRadioButton
        }
    }
}

Я искал пару дней примеры или объяснения того, как получить доступ к родительской оболочке, и я не могу понять это. Следует отметить, что это мой первый UWP в Windows 10, и я новичок в C#.

Кроме того, если это помогает или уместно, приведенный ниже код находится внутри файла Shell.xaml.cs, который я использую для перехода к отдельным страницам.

private void HomeRadioButton_Click(object sender, RoutedEventArgs e)
{
    var frame = this.DataContext as Frame;
    Page page = frame?.Content as Page;

    if (page?.GetType() != typeof(Home))
    {
        frame.Navigate(typeof(Home));
    }
}

ОБНОВЛЕНИЕ: Итак, я внес некоторые изменения по сравнению с первым предоставленным ответом, и, похоже, у меня что-то не так с моей областью действия внутри файла Shell.xaml.

Вот мой файл Shell.xaml:

<Page
x:Class="Team_Management_Hub.Shell"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Team_Management_Hub"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:pages="using:Team_Management_Hub.Pages"
mc:Ignorable="d">
<pages:Home MyCoolEvent="OnCoolEvent"/>;
<SplitView x:Name="Team_Management_Hub" Background="Black" OpenPaneLength="240" CompactPaneLength="48"
    DisplayMode="CompactOverlay" IsPaneOpen="False" PaneBackground="Gray" Content="{Binding}">
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup>
            <VisualState x:Name="HardwareButtons">
                <VisualState.Setters>
                    <Setter Target="BackRadioButton.Visibility" Value="Collapsed" />
                </VisualState.Setters>
            </VisualState>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>
    <SplitView.Pane>
        <StackPanel x:Name="SplitViewPanePanel">
            <RadioButton x:Name="BackRadioButton" Click="BackRadioButton_Click" Style="{StaticResource NavRadioButtonStyle}" Tag="&#xE112;" Background="Gray" Content="Back" GroupName="Back"/>
            <RadioButton x:Name="HamburgerRadioButton" Click="HamburgerRadioButton_Click" Style="{StaticResource NavRadioButtonStyle}" Tag="&#xE700;" Content="Menu" />
            <RadioButton x:Name="HomeRadioButton" Click="HomeRadioButton_Click" Style="{StaticResource NavRadioButtonStyle}" Tag="&#xE80F;" Content="Home" GroupName="Navigation"/>
            <RadioButton x:Name="TARadioButton" Click="TARadioButton_Click" Style="{StaticResource NavRadioButtonStyle}" Tag="&#xE179;" Content="Team Assignments" GroupName="Navigation"/>
            <RadioButton x:Name="ASRRadioButton" Click="ASRRadioButton_Click" Style="{StaticResource NavRadioButtonStyle}" Tag="&#xE13C;" Content="Assignment Switch Requests" GroupName="Navigation"/>
            <RadioButton x:Name="MTRadioButton" Click="MTRadioButton_Click" Style="{StaticResource NavRadioButtonStyle}" Tag="&#xE15E;" Content="Management Tools" GroupName="Navigation"/>
        </StackPanel>
    </SplitView.Pane>
</SplitView>

With this, everything under <pages:Home MyCoolEvent="OnCoolEvent"/> gets underlined blue, and the error "the property Content is set more than once" I found this link and so I tried to implement putting it all in a grid, but when I simply add <Grid> above the <SplitView> and below the final </SplitView> if I keep the <pages> portion above the splitview, the button on the Home.xaml page doesn't do anything. If I move the <pages> to below the <SplitView> but still inside the <Grid></Grid> the button works, but the SplitView disappears. I also tried throwing the <pages> inside the <StackPanel> that holds my RadioButtons, but it does something weird, where it appears my Home Page is inside the SplitView Pane under the buttons. So, I'm sure I've got some simple mistake I'm making with the scope of the xaml setup, but I've tried so many combinations of placing the <pages:Home> in so many different areas and inside different controls, and I haven't gotten it to work. So, some help on the proper layout to make this work, would be great.

Спасибо за любую помощь.


person TekGiant    schedule 20.08.2015    source источник


Ответы (1)


Очень простым подходом было бы добавить событие в ваш домашний класс. Когда TestButton щелкнут, запустите событие. Затем вы будете прослушивать событие на своей странице «оболочки».

пример оболочки xaml:

<pages:Home MyCoolEvent="OnCoolEvent"/>

пример шелл-кода

private void OnCoolEvent(object sender, EventArgs args)
{
   //alter the visibility of the MTRadioButton
}

Домашний код:

public event EventHandler MyCoolEvent;

private void TestButton_Click(object sender, RoutedEventArgs e)
{
    OnMyCoolEvent();
}

protected virtual void OnMyCoolEvent()
{
    EventHandler handler = MyCoolEvent;
    if (handler != null) handler(this, EventArgs.Empty);
} 
person Shawn Kendrot    schedule 20.08.2015