2013-02-19 58 views
0

无论如何在Silverlight中向所有文本框控件添加右键单击事件而无需手动将其添加到整个项目中的每个控件?在Silverlight中将右键单击事件连接到所有文本框

做这样:

<TextBox x:Name="txtName" MouseRightButtonUp="txtName_MouseRightButtonUp" 
    MouseRightButtonDown="txtName_MouseRightButtonDown" /></TextBox> 

然后固定在的.cs事件约50+(希望这只是50+)文本框可能需要一段时间。

如果不是,那么最简单的方法是什么?

回答

1

您可扩展的文本框

class SimpleTextBox 
{ 
    public SimpleTextBox() 
    { 
     DefaultStyleKey = typeof (SimpleCombo); 
     MouseRightButtonDown += OnMouseRightButtonDown; 
    } 

    private void OnMouseRightButtonDown(object sender, MouseButtonEventArgs 
mouseButtonEventArgs) 
    { 
     //TODO something 
    } 
} 

==========

并使用此控制。 或作为替代解决方案 - 您可以创建行为:

CS: ... using System.Windows.Interactivity;

public class TextBoxBehavior : Behavior<TextBox> 
{ 
    protected override void OnAttached() 
    { 
     base.OnAttached(); 
     AssociatedObject.MouseRightButtonDown += AssociatedObject_MouseRightButtonDown; 
    } 

    protected override void OnDetaching() 
    { 
     base.OnDetaching(); 
     AssociatedObject.MouseRightButtonDown -= AssociatedObject_MouseRightButtonDown;   
    } 

    private void OnMouseRightButtonDown(object sender, MouseButtonEventArgs mouseButtonEventArgs) 
    { 
     e.Handled = true; 
     // DO SOMETHING 
    } 
} 

XAML:

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" 

<TextBox ...> 
    <i:Interaction.Behaviors> 
     <local:TextBoxBehavior /> 
    </i:Interaction.Behaviors> 
</TextBox> 

,并附这个处理程序到你的文本框大将风范。

+0

直到我添加了标记来指定行为后才起作用。看起来我必须手动执行该操作。我正在考虑某种方式,以便其他编码人员不需要添加这些编码。 – Bahamut 2013-02-19 07:42:58

+0

好吧,我开玩笑。我更新了帖子,并将链接添加到描述如何将行为添加到样式的帖子中。 – Bahamut 2013-02-19 10:29:32

+0

虽然海报仍然没有接受我的编辑。 更新:请参阅http://stackoverflow.com/questions/13498216/attach-behaviour-to-all-textboxes-in-silverlight您可以忽略xaml代码并继续使用样式代替 – Bahamut 2013-02-19 12:15:15

1

我对this question的回答也是你的问题的答案。

简而言之,从TextBox派生一个类型可能是最容易的,将您的MouseRightButtonDown事件处理程序放在那里,并用您的类型替换所有现有的textBox实例。