SilverLight学习笔记--如何解决Button不响应MouseLeftButtonDown与MouseLeftButtonUp事件的问题

时间:2021-10-18 09:32:18

在Silverlight 2 中的按钮不能响应MouseLeftButtonDown 和 MouseLeftButtonUp 事件,为解决此问题,我们可通过创建自定义按钮控件加以解决,
1、创建自定义按钮控件,参见"SilverLigth学习笔记--如何在Silverlight中创建自定义Button控件"一文。

2、创建新项目,在新项目中引用前面创建的MyButton自定义按钮(即引入MyButton.dll)。并在xaml文件头部中加入如下代码?:

 

xmlns:myContron = " clr-namespace:MyButton;assembly=MyButton "

 

3、添加一个自定义按钮和两个TextBlock控件,添加后的完整代码如下:

 

< UserControl x:Class = " ButtonMouseLeftClick.Page "
    xmlns
= " http://schemas.microsoft.com/winfx/2006/xaml/presentation "  
    xmlns:x
= " http://schemas.microsoft.com/winfx/2006/xaml "  
    xmlns:myContron
= " clr-namespace:MyButton;assembly=MyButton "
    Width
= " 400 "  Height = " 300 " >
   
< Canvas Width = " 300 "  Height = " 400 "  Background = " Coral " >
        
< myContron:MyButton Width = " 200 "  Height = " 50 "  Canvas.Top = " 50 "  Canvas.Left = " 50 "  Content = " Click Me "
            MouseLeftButtonDown
= " MyButton_MouseLeftButtonDown "  MouseLeftButtonUp = " MyButton_MouseLeftButtonUp "   >
        
</ myContron:MyButton >
            
< TextBlock x:Name = " TextBlock1 "  Width = " 80 "  Height = " 20 "  Canvas.Top = " 140 "  Canvas.Left = " 80 "   Text = " TextBlock1 " ></ TextBlock >
         
< TextBlock x:Name = " TextBlock2 "  Width = " 80 "  Height = " 20 "  Canvas.Top = " 180 "  Canvas.Left = " 80 "   Text = " TextBlock2 " ></ TextBlock >
    
</ Canvas >
</ UserControl >

 

4、添加后台处理代码

 

private   void  MyButton_MouseLeftButtonDown( object  sender, MouseButtonEventArgs e)

{

this .TextBlock2.Text  =  String.Empty;

this .TextBlock1.Text  =   " Down " ;

}

 

private   void  MyButton_MouseLeftButtonUp( object  sender, MouseButtonEventArgs e)

{

this .TextBlock1.Text  =   " Up "

}

 

5、生成项目运行即可看到结果

 

前往:Silverlight学习笔记清单