0

so here it is:

Bowls = new ObservableCollection<Bowl>();

SowCommand = new DelegateCommand(param => SowGame(param));

private void SowGame(Object param)
{
Int32 index = Convert.ToInt32(param);

Bowls[index] = ...
}

So i pass "param" to SowGame by pressing a button Command="{Binding SowCommand}"

param is now an object of Bowl type

in SowGame i want to do something with this Bowl object and i know a certain object from a collection can be reached by using Bowls[index of object]. But converting the object to int as above doesn't seem to work.

How can i get the index of the passed object?

4

2 回答 2

1

Use IndexOf method of your ObservableCollection:

int index = Bowls.IndexOf((Bowl)param);
于 2012-12-03T18:30:49.610 回答
0

I figured it out! Here's what caused the problem:

SowCommand = new DelegateCommand(param => SowGame(param));

To be able to get the index of the pressed button (which is bound to the above command) you need two things:

First you need to implement a function which somehow computes the index of an element in a collection. For example in my case:

public Int32 Number { get {

            if (Y == 0)
            {
                return _Size - 1 - X;
            }
            else
            {
                return _Size + X;
            }

        } }

Of course the method of getting the index depends on the problem. The above code is a part of the implementation of my Bowl type.

After this you have to add

Command Parameter="{Binding Number}"

to your .xaml and the code in the question should work properly.

于 2012-12-04T17:50:21.740 回答