[英]How to get index of object in observablecollection passed as parameter
所以這里是:
Bowls = new ObservableCollection<Bowl>();
SowCommand = new DelegateCommand(param => SowGame(param));
private void SowGame(Object param)
{
Int32 index = Convert.ToInt32(param);
Bowls[index] = ...
}
因此,我通過按下按鈕Command =“ {Binding SowCommand}”將“ param”傳遞給SowGame
參數現在是Bowl類型的對象
在SowGame中,我想對此Bowl對象進行操作,並且我知道可以通過使用Bowls [object index]來訪問集合中的某個對象。 但是如上所述將對象轉換為int似乎不起作用。
如何獲取傳遞對象的索引?
使用ObservableCollection的IndexOf方法:
int index = Bowls.IndexOf((Bowl)param);
我想到了! 造成問題的原因如下:
SowCommand = new DelegateCommand(param => SowGame(param));
為了獲得按下按鈕的索引(綁定到上述命令),您需要做兩件事:
首先,您需要實現一個函數,該函數以某種方式計算集合中元素的索引。 例如我的情況:
public Int32 Number { get {
if (Y == 0)
{
return _Size - 1 - X;
}
else
{
return _Size + X;
}
} }
當然,獲取索引的方法取決於問題。 上面的代碼是我的Bowl類型實現的一部分。
在此之后,您必須添加
Command Parameter="{Binding Number}"
到您的.xaml ,問題中的代碼應該可以正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.