Usman Ali
Usman Ali

Reputation: 818

Get item from CollectionViewSource using index number

I'm using CollectionViewSource as ItemSource in DataGrid

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

and the CollectionViewSource is bound to ObservableCollection in ViewModel

private ObservableCollection<LevelModel> mLevelSource;
public ObservableCollection<LevelModel> LevelSource
{
     get
     {
         mLevelSource = mLevelSource ?? new ObservableCollection<LevelModel>();
         return mLevelSource;
     }
}


public CollectionViewSource CollViewSource { get; set; }

Model

public class LevelModel : BaseViewModel
{
    public string Level_Title { get; set; }
    ...

In Constructor

CollViewSource = new CollectionViewSource();
CollViewSource.Source = LevelSource;

I have Button inside DataGrid

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

What I want, when i click the Button .i.e ViewCommand it should fetch Level_Title or some other item by Index Number

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;
    }
}

For example when index number is 3 then it should fetch the item that exist on 3rd index

Note: I don't want to involve SeletedItem

Upvotes: 1

Views: 895

Answers (1)

Tomtom
Tomtom

Reputation: 9394

Try the following on your CollectionView:

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

Upvotes: 1

Related Questions