2014-12-04 63 views
0

我使用一個ItemsControl顯示項目和刪除/向上/向下移動他們:不能在我的WPF項目進入一個ObservableCollection的DataContext的參數在一個ItemsControl

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

我想選擇的ObservableCollection爲test1的指標(關鍵) ist項目。

removebutton.DataContext.ToString();工作正常,我得到一個字符串與鍵和值。

但我只需要密鑰,並且不起作用:removebutton.DataContext.Key;(錯誤:無法解析符號'密鑰')。

如果我調試,我可以訪問關鍵:

enter image description here

+2

你有沒有嘗試將DataContext轉換爲KeyValuePair? – Jawahar 2014-12-04 08:53:34

回答

1

你需要投removebutton.DataContextKeyValuePair<int, string>,因爲的DataContext的類型是object

這將工作:

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

哦,親愛的!謝謝你和XAML愛人 – Stampy 2014-12-04 08:56:32

相關問題