Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding a function to the MouseDown event in xaml?

Tags:

c#

mvvm

wpf

xaml

im Working on learning WPF and C# programming at the moment but im struggling with understanding bindings etc.

I am stuck on "binding" functions or commands to my XAML object which is in a grid.

<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()}"/>

The code MouseDown="{Binding Path=ChessPieces[0].Move()}" Does not work but displays what im trying to achive

In my viewmodel i have defined a list which i have filled up with instances of my diffrent chesspieces, and then im planning on binding each image to a instance from that list.

im trying to do is bind the MouseDown function at the moment, it seems like if i place the function in the Mainwindow.xaml.cs file it can access it. But i want it to be able to access it from the model

Mainwindow.xaml.cs

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

    }
}

The BlkRook object has defined Row, column, name and a function move at the moment.

Error Message:

"'TheGame.Views.MainWindow' does not contain a definition for 'Move' and no extension method 'Move' accepting a first argument of type 'TheGame.Views.MainWindow' could be found (are you missing a using directive or an assembly reference?)"

So.. How do i bind a function that is defined in a Model-object to a XAML object?

Thanks

/Martin

like image 842
Martin Avatar asked Dec 03 '13 16:12

Martin


1 Answers

You can't bind to methods. You are using MVVM so I would suggest you to use attached properties in combination with commands. You could also use the MouseBinding class: http://msdn.microsoft.com/en-us/library/system.windows.input.mousebinding(v=vs.110).aspx. Commandbinding is explained quite well here: 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>
like image 75
Florian Avatar answered Nov 09 '22 11:11

Florian