不会触发MouseBinding命令

时间:2016-03-09 11:06:06

标签: c# wpf xaml binding command

这是我的XAML代码:

<Grid>
    <Grid.InputBindings>
        <MouseBinding Gesture="LeftDoubleClick" Command="{Binding MouseDblClick}" />
    </Grid.InputBindings>
</Grid>

和我的代码隐藏:

private RelayCommand _MouseDoubleClick;

public ICommand MouseDblClick
{
    get
    {
        if (_MouseDoubleClick == null)
        {
            _MouseDoubleClick = new RelayCommand(param => Clicked());
        }

        return _MouseDoubleClick;
    }
}

private void Clicked()
{
    MessageBox.Show("Works");
}

我希望在双击网格后显示messageBox。但没有任何反应。哪里出错?

2 个答案:

答案 0 :(得分:2)

正如他在评论中提到的icebat。尝试将Grid的BG设置为Brush

<Grid Background="Green">
    <Grid.InputBindings>
        <MouseBinding Gesture="LeftDoubleClick" Command="{Binding MouseDblClick}" />            
    </Grid.InputBindings>
</Grid>

默认情况下,GridBackground="{x:Null}"无法点击,如上所述here

此外,请确保您已将VM对象传递到DataContext

View

像这样this.DataContext = new ViewModel();

答案 1 :(得分:0)

建议另一种解决方案:

我不是Commands的粉丝,我有另一种基于Trigger Events的解决方案,如果它可以帮到你:

1)添加对System.Windows.Interactivity和Microsoft.Expression.Interactions DLL的引用(在C:\ Program Files(x86)\ Microsoft SDKs \ Expression \ Blend.NETFramework \ v4.0 \ Libraries中找到)

2)将其添加到您的XAML文件中:

 xmlns:l="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
 xmlns:ei="clr-namespace:Microsoft.Expression.Interactivity.Core;assembly=Microsoft.Expression.Interactions"

3)在你的网格中添加:

<Grid...>
     <l:Interaction.Triggers>
          <l:EventTrigger EventName="DoubleClick">
                 <ei:CallMethodAction TargetObject="{Binding}"
                          MethodName="Clicked" />
          </l:EventTrigger>
     </l:Interaction.Triggers>
...
</Grid>

4)使你的方法“Clicked()”Public

我希望这会对你有所帮助。