[英]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: 在我的WPF项目中,我使用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;
}
}
I want to get the index (Key) of the selected ObservableCollection TestList item. 我想获取所选ObservableCollection TestList项目的索引(键)。
The removebutton.DataContext.ToString();
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;
但是我只需要Key,那是行不通的:
removebutton.DataContext.Key;
(Error: Cannot resolve symbol 'Key'). (错误:无法解析符号“键”)。
If I debug, I can access the Key: 如果我调试,则可以访问密钥:
You need to cast removebutton.DataContext
to KeyValuePair<int, string>
, since DataContext's type is object
您需要将
removebutton.DataContext
为KeyValuePair<int, string>
,因为DataContext的类型是object
This will work: 这将起作用:
var test = ((System.Collections.Generic.KeyValuePair<int, string>)removebutton.DataContext).Key
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.