paparazzo
paparazzo

Reputation: 45096

Get DataContext from TextBlock MouseDown

Bound column in a ListView GridView

How to get the DataSource in a MouseDown event

<GridViewColumn.CellTemplate>
    <DataTemplate>  
         <TextBlock Text="{Binding Path=Name, Mode=OneWay}" 
                    MouseDown="NameCol_mousedown"/>
    </DataTemplate>
</GridViewColumn.CellTemplate>

This works in another project with a button in a ListView.

This is what it tried ...

Error Unable to cast object of type 'MS.Internal.NamedObject' to type 'ListViewDragDrop.DocProp'.

The DataSource is DocProp.

private void NameCol_mousedown(object sender, MouseButtonEventArgs e)
{
    TextBlock tb = (TextBlock)sender;
    object data = tb.DataContext;
    dataSource = (DocProp)tb.DataContext;
}

Upvotes: 4

Views: 6915

Answers (2)

Nobody
Nobody

Reputation: 341

For anyone still having problems, this works fine as well.

private void MenuItem_Click(object sender, RoutedEventArgs e)
{
    var baseobj = sender as FrameworkElement;
    var myObject = baseobj.DataContext as (Object you expect);

    // Example: var myObject = baseobj.DataContext as Dog;
    // myObject.Bark();
}

Upvotes: 3

Vinit Sankhe
Vinit Sankhe

Reputation: 19885

try this...

private void NameCol_mousedown(object sender, MouseButtonEventArgs e)
{
    var tb = (TextBlock)e.OriginalSource;
    var dataCxtx = tb.DataContext;
    var dataSource = (DocProp)dataCxtx;
}

Upvotes: 12

Related Questions