C# UWP按钮未触发事件

C# UWP按钮未触发事件,c#,xaml,uwp,C#,Xaml,Uwp,我在做一个UWP项目。我有两个按钮从一页转到另一页。但我不明白为什么从来没有调用过按钮,我尝试了不同的教程和技巧,但都不起作用 <Page x:Class="MultiplatformMvvm.UWP.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

我在做一个UWP项目。我有两个按钮从一页转到另一页。但我不明白为什么从来没有调用过按钮,我尝试了不同的教程和技巧,但都不起作用

<Page
    x:Class="MultiplatformMvvm.UWP.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:MultiplatformMvvm.UWP"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    <Page.Resources>
        <ResourceDictionary>

            <Style x:Key="textBlockStyle" TargetType="TextBlock">
                <Setter Property="Margin" Value="12,20,12,12"/>
                <Setter Property="HorizontalAlignment" Value="Center"/>
                <Setter Property="FontSize" Value="24"/>
            </Style>

            <Style x:Key="buttonStyle" TargetType="Button">
                <Setter Property="Margin" Value="12"/>
                <Setter Property="HorizontalAlignment" Value="Center"/>
                <Setter Property="Background" Value="Purple"/>
                <Setter Property="Foreground"  Value="White"/>
            </Style>

        </ResourceDictionary>
    </Page.Resources>

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <StackPanel>
            <TextBlock Text="Un café !" Style="{StaticResource textBlockStyle}"/>
            <Button x:Name="coffeeButton" Style="{StaticResource buttonStyle}" >
                Go Coffee
            </Button>
            <Button x:Name="myContactsButton" Style="{StaticResource buttonStyle}">
                My contacts
            </Button>
        </StackPanel>
    </Grid>
</Page>
您是否尝试过: -将处理程序附加到xaml本身中的按钮,并查看它是否正常工作? -如果您正在使用绑定,那么是否添加命令绑定

同样在您的场景中,请尝试以下操作: 在构造函数的InitializeComponent()之后;加:

加载+=(s,e)=>{coffeeButton.单击+=coffeeButton\u Click;}


看看这是否有效。

我终于清理了UWP项目中的所有缓存,并进行了重建,它终于可以工作了。
希望它对其他人有所帮助。

在呈现UI之前,您正在创建单击事件。这就是为什么没有创建click事件(至少我了解到这一点)的原因。在UI本身中尝试一下<代码>我试过了,但不起作用。你有错误吗?或者单击/点击事件没有被触发?没有错误,只是什么都没有发生。我建议你把你在这个问题上的经验作为一个答案,并将其标记为已接受,这样其他有同样问题的人将受益。你能给我们按钮样式吗?是否可能在样式中重写某些行为?在UWP应用程序中,由于您的应用程序将在移动设备上运行,因此最好在用户点击时触发点击事件,在鼠标点击时触发点击事件。如果清除代码并清除其工作的构建项目,这是一个缓存问题…:(谢谢你的帮助!谢谢你分享你的建议。它也解决了我同样的问题。
public sealed partial class MainPage : Page
{
    public MainPage()
    {
        InitializeComponent();
        coffeeButton.Click += coffeeButton_Click;
    }

    void coffeeButton_Click(object sender, RoutedEventArgs e)
    {
        // I never enter here
        Frame.Navigate(typeof(CoffeeListPage));
    }

    private void myContactsButton_Click(object sender, RoutedEventArgs e)
    {
        // I never enter here
        Frame.Navigate(typeof(ContactListPage));
    }
}