从TextBlock MouseDown获取DataContext

时间:2013-06-23 21:09:57

标签: c# .net wpf listview mouseevent

ListView GridView中的绑定列

如何在MouseDown事件中获取DataSource

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

这适用于另一个带有ListView按钮的项目。

这就是它的尝试......

错误无法将“MS.Internal.NamedObject”类型的对象强制转换为“ListViewDragDrop.DocProp”。

DataSource是DocProp。

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

2 个答案:

答案 0 :(得分:4)

试试这个......

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

答案 1 :(得分:2)

对于任何仍有问题的人,这也可以。

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();
}