WPF Popup focus in data grid

送分小仙女□ 提交于 2019-11-29 04:48:18

I had a similar problem where a Popup embedded in a UserControl as a cell editing template would close when certain areas of it were clicked. The problem turned out to be that the WPF Toolkit (and presumably WPF4) DataGrid is very greedy with left mouse clicks. Even when you handle them and set Handled to true, the grid can interpret them as clicking into a different cell.

This thread has the full details, but the fix is to hook into DataGrid.CellEditEnding event and cancel the end edit:

private static void DataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
    if (e.Column.GetType() == typeof(DataGridTemplateColumn))
    {
        var popup = GetVisualChild<Popup>(e.EditingElement);
        if (popup != null && popup.IsOpen)
        {
            e.Cancel = true;
        }
    }   
}

private static T GetVisualChild<T>(DependencyObject visual)
    where T : DependencyObject
{
    if (visual == null)
        return null;

    var count = VisualTreeHelper.GetChildrenCount(visual);
    for (int i = 0; i < count; i++)
    {
        var child = VisualTreeHelper.GetChild(visual, i);

        var childOfTypeT = child as T ?? GetVisualChild<T>(child);
        if (childOfTypeT != null)
            return childOfTypeT;
    }

    return null;
}

Full credit for this goes to the Actipro thread.

Not sure if this will help anyone, but this helps if you have custom controls in the datagrid with a popup..... this fixed my problem, and it was one line of xaml. I spend the whole day re-reading this forum and then looking at the source for DataGridCell. Hope this helps.

    <Style TargetType="{x:Type DataGridCell}">
        <Setter Property="Focusable" Value="False"></Setter>
    </Style>

I had a kinda simular problem, i created a usercontrol containing a textbox, a button and a calendar. Basicaly i create my own datepicker with custom validation logic.

I put this component in a CellEditingTemplate. When i pressed the button, the popup showed, but clicking the popup anywhere caused the cell te stop editing (because the popup was taking focus from the textbox). I solved it by adding code that sais that if the popup is open, the focus of the textbox may not be lost. This did the trick for me.

Also, the in the on loaded event handler of the usercontrol i give focus to the textbox. In your case it's propably the Usercontrol itsefl that has focus.

protected override void OnPreviewLostKeyboardFocus(KeyboardFocusChangedEventArgs e) {
             // Don't allow focus to leave the textbox if the popup is open
             if (Popup.IsOpen) e.Handled = true;  
}

private void Root_Loaded(object sender, RoutedEventArgs e) {
       TextBox.Focus();
}

Set FocusManager.IsFocusScope Attached Property on the Popup to True

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!