2010/08/31

WPF: Get the item in the ListView under the mouse cursor.

How to get the item in the ListView under the mouse cursor. These codes are gethered at CodeProject here.

// A ListView control named lv. Let’s do something in MouseDoubleClick event handler.
private void
lv_MouseDoubleClick(object sender, MouseButtonEventArgs e) {
    int index = GetCurrentIndex(e.GetPosition); 
    MyClass instance = lvUsers.Items[index] as MyClass
    // Now you got the original object and then do what you want. 
}
delegate Point GetPositionDelegate(IInputElement element);
private int GetCurrentIndex(GetPositionDelegate getPosition) {
    int index = -1;
    for (int i = 0; I < lv.Items.Count; i++) {
        ListViewItem item = GetListViewItem(i);
        if (item == null)
            continue;
        if (IsMouseOverTarget(item, getPosition)) {
            index = i;
            break;
        }
    }
    return index;
}
private ListViewItem GetListViewItem(int index) {
    if (lv.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated)
    return null;
    return lv.ItemContainerGenerator.ContainerFromIndex(index) as ListViewItem;
}
private bool IsMouseOverTarget(Visual target, GetPositionDelegate getPosition) {
    Rect bounds = VisualTreeHelper.GetDescendantBounds(target);
    Point mousePos = getPosition((IInputElement)target); 
    return bounds.Contains(mousePos);
}

2010/08/30

WPF: Binding a ListView to DataTable

Suppose you have a DataTable filled with data. And want a ListView to present the data. This code sample can help you.

XAML

<ListView Name="lv">
    <ListView.View>
        <GridView>
        </GridView>
    </ListView.View>
</ListView>

C#

string tableName = “some_table_name”;
DataSet ds = Dao.GetData(tableName);  // A class to retrieve dataset.
if (ds.Tables == null || ds.Tables.Count == 0)
    return;

GridView gv = (GridView)lv.View;

DataTable dt = ds.Tables[0];
foreach (DataColumn col in dt.Columns) {
    GridViewColumn gvCol = new GridViewColumn();
    gvCol.Header = col.ColumnName;
    gvCol.DisplayMemberBinding = new Binding(col.ColumnName);
    gvCol.Width = 100;
    gv.Columns.Add(gvCol);
}

lv.ItemsSource = ((IListSource)dt).GetList();