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?
使用ObservableCollection的IndexOf方法:
int index = Bowls.IndexOf((Bowl)param);
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.