将函数绑定到xaml中的MouseDown事件



im目前正在学习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文件中,它就可以访问它。但我希望它能够从模型访问它

主窗口.xaml.cs

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

BlkRook对象目前已经定义了Row、column、name和一个函数move。

错误消息:

"TheGame.Views.MainWindow"不包含"Move"的定义,也找不到接受类型为"TheGame.Views.MainWindow"的第一个参数的扩展方法"Move"(是否缺少using指令或程序集引用?)"

所以。。如何将Model对象中定义的函数绑定到XAML对象?

感谢

/Martin

您不能绑定到方法。您正在使用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>

最新更新