Получить элемент из CollectionViewSource, используя номер индекса - PullRequest
0 голосов
/ 30 августа 2018

Я использую CollectionViewSource в качестве ItemSource в DataGrid

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

и CollectionViewSource привязан к ObservableCollection в ViewModel

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

<DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
        <Button
            Command="{Binding DataContext.ViewCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}"
            CommandParameter="{Binding}"
            Content="View" />
    </DataTemplate>
</DataGridTemplateColumn.CellTemplate>

Что я хочу, когда я нажимаю кнопку .i.e 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, он должен выбрать элемент, который существует в третьем индексе

Примечание: Я не хочу привлекать SeletedItem

1 Ответ

0 голосов
/ 30 августа 2018

Попробуйте выполнить следующее на вашем CollectionView:

LevelModel lm = CollViewSource.View.Cast<LevelModel>().ToArray()[indexNumber];
string title = lm.Level_Title;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...