2016-11-25 79 views
0

我正在开发一个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" 
    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> 

我的C#代码:

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)); 
    } 
} 
+0

您在呈现UI之前正在创建Click事件。这就是为什么点击事件没有被创建(至少这是我的理解。)尝试在UI本身。 '

+0

我试过了但没有工作 – fandro

+0

你有错误吗?或点击/点击事件不被解雇? – AVK

回答

0

我终于清理UWP项目中的所有缓存并重建,并最终生效。 希望它可以帮助别人。

1

你试过: - 在XAML中附加一个处理程序按钮本身,看看它的作品? - 如果您使用绑定,然后添加命令绑定?

同样在你的场景中,试试这个: 在你的构造函数中InitializeComponent()之后;加:

加载+ =(s,e)=> {coffeeButton.Click + = coffeeButton_Click; };

看看是否有效。

+0

不,谢谢,这是行不通的 – fandro

+0

即使附加一个点击处理程序在xaml不工作吗? – Jinish

+0

我试过它不工作,这是疯狂的 – fandro