从触发器内调用方法

时间:2018-03-14 19:07:23

标签: c# wpf xaml

我在xaml中定义了一个跟随触发器。如何以编程方式从此Trigger中调用Test_MouseDown?

感谢您的帮助。

MyWindow.xaml

<Style.Triggers>
                    <Trigger Property="helpers:MyHelper.IsMouseLeftButtonDown" Value="True">
                        <!--Call some method present in the xaml.cs file-->
                    </Trigger>
                </Style.Triggers>

MyWindow.xaml.cs

private void Test_MouseDown(object sender, MouseButtonEventArgs e)
{

}

1 个答案:

答案 0 :(得分:0)

您可以使用行为而不是属性触发器。

首先,将以下两个程序集引用添加到项目中:

  

System.Windows.Interactivity.dll

     

Microsoft.Expression.Interactions.dll

然后在xaml文件中添加以下命名空间:

xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

然后将以下xaml代码添加到目标元素:

<Window ...>
    <i:Interaction.Triggers>
        <ei:DataTrigger Binding="{Binding Path=(helpers:MyHelper.IsMouseLeftButtonDown)}" Value="True">
            <ei:CallMethodAction MethodName="Test_MouseDown" TargetObject="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}" />
        </ei:DataTrigger>
    </i:Interaction.Triggers>
</Window>

在window.xaml.cs中,您应该提供一个名为Test_MouseDown的方法,如下所示:

    public void Test_MouseDown()
    {
        // your logic here
    }
相关问题