在Windows Phone中使用C#检测按钮向下/向上事件

时间:2013-01-01 10:34:34

标签: c# silverlight windows-phone-7 xaml

我正在学习用C#和XAML编写Windows Phone应用程序。但是我在检测按钮向下/向上事件时遇到问题。

我的XAML代码

<phone:PhoneApplicationPage
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" 
    x:Class="Tally2.MainPage"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeHuge}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait"
    shell:SystemTray.IsVisible="True">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>

        <!-- Row 0: The Header -->
        <StackPanel Grid.Row="0" Margin="24,24,0,12">
            <TextBlock Text="tap to count" Margin="-3,-8,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!-- Row 1: The text block containing the count -->
        <TextBlock x:Name="CountTextBlock" Grid.Row="1" TextAlignment="Center" Text="0" Height="259" VerticalAlignment="Top"/>

        <!-- Row 2: The reset button -->
        <Button x:Name="buttonMain" MouseLeftButtonDown="buttonMain_MouseLeftButtonDown" MouseLeftButtonUp="buttonMain_MouseLeftButtonUp" Grid.Row="1" Margin="74,240,84,117">
            <Button.Content>
                <Image x:Name="theImage" Stretch="Uniform" Source="/Images/green.png"/>
        </Button.Content>
            </Button>
    </Grid>
</phone:PhoneApplicationPage>

和C#代码

    private void buttonMain_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        Uri uri = new Uri("/Images/red.png", UriKind.Relative);
        BitmapImage imgSource = new BitmapImage(uri);
        theImage.Source = imgSource;
        theImage.Stretch = Stretch.Uniform;
    }

    private void buttonMain_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        Uri uri = new Uri("/Images/green.png", UriKind.Relative);
        BitmapImage imgSource = new BitmapImage(uri);
        theImage.Source = imgSource;
        theImage.Stretch = Stretch.Uniform;
    }

启动时未加载图像green.png。当应用程序运行并且我点击按钮时,会加载red.png,但它会一直延伸到按钮边框之外。

1 个答案:

答案 0 :(得分:1)

尝试使用Click事件而不是鼠标按下。手机上没有鼠标。

<Button x:Name="buttonMain" Click="buttonMain_MouseLeftButtonDown" Grid.Row="1" Margin="74,240,84,117">
    <Button.Content>
        <Image x:Name="theImage" Stretch="Uniform" Source="/Images/green.png"/>
    </Button.Content>
</Button>