我使用一個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;
(錯誤:無法解析符號'密鑰')。
如果我調試,我可以訪問關鍵:
你有沒有嘗試將DataContext轉換爲KeyValuePair? – Jawahar 2014-12-04 08:53:34