Force DataGrid into edit mode when using ListView for CellTemplate

1.3k views Asked by At

Greetings,

In an WPF DataGridTemplateColumn I have a CellTemplate using a ListView and a CellEditingTemplate using a DataGrid.

<DataTemplate x:Key="LimitsTemplate">
    <ListView ItemsSource="{Binding Limits}" IsEnabled="False">
        <ListView.ItemTemplate>
            ...
        </ListView.ItemTemplate>
    </ListView>
 </DataTemplate>
 <DataTemplate x:Key="LimitsEditingTemplate">
      <toolkit:DataGrid ItemsSource="{Binding Limits}" ...>
            ...
      </toolkit:DataGrid>
 </DataTemplate>

The problem I am facing is how to force the column into edit mode on double click? This is the default behaviour for the other columns and I believe for the DataGrid in general. Pressing F2 starts edit mode, but double click using mouse does not.

If I set the ListView.IsEnabled to False then the double click works, but then I have a disabled list view which doesn't look right and any style hack feels like an ugly kludge.

Note that I have tried single click editing which didn't do the trick.

Any help appreciated, thanks!

2

There are 2 answers

0
si618 On BEST ANSWER

Of course as soon as I ask SO, the answer materializes :) If I use the FindVisualParent method from the single click editing trick and wire that up to the list view double click it all works as expected:

<DataTemplate x:Key="LimitsTemplate">
    <ListView ItemsSource="{Binding Limits}" PreviewMouseDoubleClick="limitsListView_PreviewMouseDoubleClick">
    ...

and in the code behind:

static T FindVisualParent<T>(UIElement element) where T : UIElement
{
    UIElement parent = element;
    while (parent != null)
    {
        T correctlyTyped = parent as T;
        if (correctlyTyped != null)
        {
            return correctlyTyped;
        }

        parent = System.Windows.Media.VisualTreeHelper.GetParent(parent) as UIElement;
    }
    return null;
}

void limitsListView_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    DataGrid dataGrid = FindVisualParent<DataGrid>(sender as UIElement);
    if (dataGrid != null)
    {
        dataGrid.BeginEdit();
    }
}
0
Mohamed Elashi On

I had very similar problem with my DataGrid. Here is what caused the problem in my project: The ItemsSource in my DataGrid is assigned a custom list that implements IEnumerable.

I implemented this list so that it returns different object for different calls of the same index.. like if you call list[0] the first time it returns an object that holds the name "WPF" for example if you call it again list[0] it will return for you a completely new object that holds the value "WPF".

So if the collection (Limits) you are binding to, is a custom collection that you implemented IEnumerable and IList interfaces for it, then check your implementation. in my case, it was the index operator, IndexOf and Contains.

My Blog