Search code examples
c#.netwpfobservablecollectionitemscontrol

Can't access DataContext parameter of an ObservableCollection in an ItemsControl


In my WPF project I'm using an ItemsControl to show items and delete/move up/down them:

<ItemsControl ItemsSource="{Binding TestList, Mode=OneWay}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Grid>
                ...
                <TextBox IsReadOnly="True" Text="{Binding Path=Value , Mode=OneWay}" />
                <Button Content"Remove" Click="RemoveClick" />
            </Grid>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

private ObservableCollection<KeyValuePair<int, string>> TestList;

private void RemoveClick(object sender, RoutedEventArgs e)
{
    var removebutton = sender as Button;

    if (removebutton != null) 
    {
         var test = removebutton.DataContext.ToString();   // That works

         // var test removebutton.DataContext.Key;
     }
}

I want to get the index (Key) of the selected ObservableCollection TestList item.

The removebutton.DataContext.ToString(); works fine, I get a string with key and value.

But I need only the Key and that doesn't work: removebutton.DataContext.Key; (Error: Cannot resolve symbol 'Key').

If I debug, I can access the Key:

enter image description here


Solution

  • You need to cast removebutton.DataContext to KeyValuePair<int, string>, since DataContext's type is object

    This will work:

    var test = ((System.Collections.Generic.KeyValuePair<int, string>)removebutton.DataContext).Key