(XAML UWP)定义元素,包括跨多个页面(C )使用的事件



因此,我目前正在尝试集中我计划在应用程序中的多个位置使用的一些元素。例如,我有一个在应用程序的一部分中用作导航菜单的飞行,但是我遇到的问题是我无法在应用程序资源中设置"单击"事件,在app.xaml <</p>

<Application.Resources>
    <Flyout x:Key="guided_tour_nav">
        <StackPanel>
            <Button x:Name="home"  HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Content="Return to Home" Click="home_button_Click"/>
            <Button x:Name="water"  HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Content="The Water Enters"/>
            <Button x:Name="eggs"  HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Content="Eggs Arrive"/>
            <Button x:Name="pre_hatch"  HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Content="Pre-Hatching"/>
            <Button x:Name="tanks"  HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Content="The Tanks"/>
            <Button x:Name="life_support"  HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Content="Life Support"/>
            <Button x:Name="waste"  HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Content="Filtering Waste"/>
            <Button x:Name="release"  HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Content="The Release"/>
        </StackPanel>
    </Flyout>
</Application.Resources>

我在mainpage.xaml和其他一些页面中使用它

<Button Flyout="{StaticResource guided_tour_nav}" Content="Jump to Section"/>

我当前遇到错误

WMC1005 Events cannot be set in the Application class XAML file

我希望能够定义整个元素,单击事件以及所有需要在我需要的任何地方引用,而不必重新定义每个页面的点击事件。我想这一定有可能,但是我是UWP平台的新手。

创建Flyout作为Application.Resources中的资源时,您不幸的是。

但是有两种替代解决方案。

自定义用户控制

您可以将飞行器包裹到自定义的XAML用户控件中,然后轻松重复使用您想要的任何地方。

右键单击解决方案Explorer 中的UWP项目,然后选择 add - 新项目... 。在对话框中,选择 XAML 部分,然后找到用户控制选项。选择所需的名称(例如GuidedTourNav(,然后单击添加

这将创建三个文件-GuidedTourNavFlyout.xamlGuidedTourNavFlyout.xaml.hGuidedTourNavFlyout.xaml.cpp。自定义XAML控件的默认类型为UserControl。您需要更改此问题。打开GuidedTourNavFlyout.xaml文件,然后将根元素从UserControl更改为Flyout

<Flyout
    x:Class="xxxxxx"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="xxxxxxx"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
</Flyout>

最后,用您的飞行内容替换GuidedTourNavFlyout.xaml代码内的Grid,并像往常一样在代码范围内创建所需的事件处理程序。

现在您可以在任何地方使用自定义飞行。首先将XML名称空间声明添加到页面的根元素。将MyApp.CustomControls替换为自定义控件所在的名称空间。

xmlns:controls="using:MyApp.CustomControls"

现在,您可以使用复杂属性在任何地方使用您的飞行:

<Button Content="Hello">
    <Button.Flyout>
        <controls:GuidedTourNavFlyout />
    </Button.Flyout>
</Button>

使用带代码的资源词典

替代解决方案将是创建一个带有代码主题的资源词典,如下所述。但是,这种方法似乎有点干净,我无法确认它在C 中起作用。

最新更新