Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all articles
Browse latest Browse all 18858

DataContext and 'System.InvalidCastException'

$
0
0

I have ListBox of 'SpecialDrive' items, each consists of a item name and delete button (and a few other)

<DataTemplate DataType="{x:Type local:SpecialDrive}"><StackPanel Orientation="Horizontal" ><TextBlock Text="{Binding fname}" /><Button Content="Delete" PreviewMouseDown="BtnSpecialDriveDelete"   >

On button click, it should be removed from the list so I tried

private void BtnSpecialDriveDelete(object sender, RoutedEventArgs e)
{
  Button itemClicked = (Button)sender;
  SpecialDrive data = (SpecialDrive)itemClicked.DataContext;

which results in :

Unable to cast object of type 'MS.Internal.NamedObject' to type 'WpfApplication1.SpecialDrive'.

I have also tried:

SpecialDrive item = ((Button)sender).DataContext as SpecialDrive;

which results in item=null

And I have tried:

Button itemClicked = (Button)sender;
object data = (object)itemClicked.DataContext;

but then data is "{DisconnectedItem}"

Please help me understand what am I doing wrong.

PS:

ObservableCollection<object> _DriveCollection = new ObservableCollection<object>();
(it is object since I have items of different type there)

 




Viewing all articles
Browse latest Browse all 18858

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>