我将CollectionViewSource用作DataGrid中的ItemSource
<DataGrid
ItemsSource="{Binding CollViewSource.View}"
SelectedIndex="{Binding IndexNumber}"
...
并且CollectionViewSource绑定到ViewModel中的ObservableCollection
private ObservableCollection<LevelModel> mLevelSource;
public ObservableCollection<LevelModel> LevelSource
{
get
{
mLevelSource = mLevelSource ?? new ObservableCollection<LevelModel>();
return mLevelSource;
}
}
public CollectionViewSource CollViewSource { get; set; }
型号
public class LevelModel : BaseViewModel
{
public string Level_Title { get; set; }
...
在构造函数中
CollViewSource = new CollectionViewSource();
CollViewSource.Source = LevelSource;
我在DataGrid中有Button
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button
Command="{Binding DataContext.ViewCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}"
CommandParameter="{Binding}"
Content="View" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
我想要的是,当我单击按钮时。即ViewCommand,它应按索引号获取Level_Title或其他项目
private ICommand mViewCommand;
public ICommand ViewCommand
{
get
{
if (mViewCommand == null)
{
mViewCommand = new DelegateCommand(delegate ()
{
int indexNumber = IndexNumber;
//string title = // logic should go here
});
}
return mViewCommand;
}
}
例如,当索引号为3时,它应该获取第3个索引上存在的项目
注意:我不想涉及SeletedItem
答案 0 :(得分:1)
在您的CollectionView上尝试以下操作:
LevelModel lm = CollViewSource.View.Cast<LevelModel>().ToArray()[indexNumber];
string title = lm.Level_Title;