Question

I have a listview that is populated from an XML file using DataTemplates. On every row a button is generated. When you click on the button I want to do something with the values on that row. So far so good.

I'm actually using the third answer from this thread here.

The actual code (with cryptic comment) from this solution is:

    private void btnMoveFDAup(object sender, RoutedEventArgs e)
{
    Button btn = ((Button)sender);
    // btn.DataContext will get you to the row object where you can retrieve the ID
}

When I look at btn.DataContext in the Watch Window of the Debugger I see all the wonderful data that I need: Watch window output

The problem is: HOW DO I ACCESS THIS DATA? I need to pull in 'Name' and a couple of booleans; but I'm completely clueless.

Various attempts like

string name = btn.DataContext.Name;

Just throw compiler errors.

Thanks in advance!

Was it helpful?

Solution

You need to cast btn.DataContext to LVData:

var lvData = (LVData)btn.DataContext;
// now you can access lvData.Name, ...

You receive a compile error because btn.DataContext is of type object and doesn't know anything about LVData members. At runtime, it can point to any class instance (because all classes inherit from object). You tell the compiler that btn.DataContext points to a LVData instance by casting it.

(More explanations here: polymorphism, casting. You will need this all the time.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top