【问题标题】:Binding a function to the MouseDown event in xaml?将函数绑定到 xaml 中的 MouseDown 事件?
【发布时间】:2013-12-03 16:02:33
【问题描述】:

我目前正在学习 WPF 和 C# 编程,但我正在努力理解绑定等。

我被困在网格中的 XAML 对象的“绑定”函数或命令上。

<Image x:Name="BlkRook1" Source="../Data/BlkRook.png" Grid.Row="{Binding Path=ChessPieces[0].Row}" Grid.Column="{Binding Path=ChessPieces[0].Column}" MouseDown="{Binding Path=ChessPieces[0].Move()}"/>

代码MouseDown="{Binding Path=ChessPieces[0].Move()}" 不起作用,但会显示我试图达到的目标

在我的视图模型中,我定义了一个列表,其中填充了我的不同棋子的实例,然后我计划将每个图像绑定到该列表中的一个实例。

我目前正在尝试绑定 MouseDown 函数,似乎如果我将该函数放在 Mainwindow.xaml.cs 文件中它可以访问它。但我希望它能够从模型中访问它

Mainwindow.xaml.cs

namespace TheGame.Views
{
    public partial class MainWindow : Window   
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new ChessBoardViewModel();
        }

    }
}

BlkRook 对象此时已定义行、列、名称和函数移动。

错误信息:

"'TheGame.Views.MainWindow' 不包含'Move' 的定义,并且找不到接受'TheGame.Views.MainWindow' 类型的第一个参数的扩展方法'Move'(您是否缺少 using 指令还是程序集参考?)”

那么.. 我如何将模型对象中定义的函数绑定到 XAML 对象?

谢谢

/马丁

【问题讨论】:

  • 为什么不将 View 命令绑定到一个新的 ViewModel 方法,然后从相应的 Model 对象调用 Move?因此:View-ViewModel-Model
  • @bland 这不是尖叫吗,即A 'Binding' cannot be set on the 'AddMouseDownHandler' property of type 'Border'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.

标签: c# wpf xaml mvvm


【解决方案1】:

您不能绑定到方法。您正在使用 MVVM,因此我建议您将附加属性与命令结合使用。您还可以使用 MouseBinding 类:http://msdn.microsoft.com/en-us/library/system.windows.input.mousebinding(v=vs.110).aspx。 命令绑定在这里解释得很好:http://www.danharman.net/2011/08/05/binding-wpf-events-to-mvvm-viewmodel-commands/

<Button>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="MouseDown" >
            <i:InvokeCommandAction Command="{Binding MouseDownCommand}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>

【讨论】:

  • 感谢您的回答,链接确实解释了很多。
  • 不幸的是,在命令中,无法再获得对Button 的引用。另外,MouseDown 事件的参数在哪里,例如指示按下了哪个按钮(不使用链接文章中提到的第 3 方库)?
  • 你可以使用InvokeCommandActionCommandParameter属性。
猜你喜欢
  • 1970-01-01
  • 2017-12-14
  • 2013-02-11
  • 1970-01-01
  • 1970-01-01
  • 2014-01-05
  • 1970-01-01
  • 1970-01-01
  • 2018-11-09
相关资源
最近更新 更多