c# - 使用索引号从 CollectionViewSource 获取项目

标签 c# wpf mvvm

我在 DataGrid 中使用 CollectionViewSource 作为 ItemSource

<DataGrid
    ItemsSource="{Binding CollViewSource.View}"
    SelectedIndex="{Binding IndexNumber}"
    ...

并且 CollectionViewSource 绑定(bind)到 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 个索引上的项目

注:我不想涉及 SelectedItem

最佳答案

在您的 CollectionView 上尝试以下操作:

LevelModel lm = CollViewSource.View.Cast<LevelModel>().ToArray()[indexNumber];
string title = lm.Level_Title;

关于c# - 使用索引号从 CollectionViewSource 获取项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52089081/

相关文章:

c# - 为什么 ClickOnce 下载未更改的文件?

c# - 使用项目内的按钮删除 ListboxItem,而不选择项目

wpf - 在 MVVM 中的查看模式和编辑模式之间切换?

c# - 如何绑定(bind)到父集合 MVVM WPF 中的特定项目

java - MVVM - 如何将上下文传递给存储库类?

c# wpf MVVM 从 ObservableDictionary 获取 ObservableList

c# - Mac OS 上的 unity 3d build 问题

c# - WCF/客户端应用程序——业务逻辑应该放在哪里?

c# - 我在这个谓词链中缺少什么?

c# - Visual Studio c# 相对路径,程序搜索两个路径,即使它找到了正确的路径