DataGridComboBoxColumn - автоматическое раскрывающееся меню одним щелчком - PullRequest
8 голосов
/ 08 ноября 2011

У меня есть DataGridComboBoxColum в DataGrid.Я хотел бы иметь возможность щелкнуть ячейку один раз и выпустить выпадающий список.В настоящее время я должен нажать несколько раз.

  <DataGrid AutoGenerateColumns="False" Height="148" HorizontalAlignment="Left" Margin="48,85,0,0" Name ="dg_display" VerticalAlignment="Top" Width="645"  CanUserAddRows="False" CanUserDeleteRows="False" ItemsSource="{Binding}" SelectionChanged="DgDisplaySelectionChanged">
        <DataGrid.Columns>
            <DataGridTextColumn IsReadOnly="True" Header="Symbol" Binding="{Binding Symbol}" />
            <DataGridTextColumn IsReadOnly="True" Header="Company ID" Binding="{Binding CompanyID}" />
            <DataGridComboBoxColumn IsReadOnly="False" Header="Sector" SelectedValueBinding="{Binding Sector}" DisplayMemberPath="{Binding [0]}" Visibility="Visible" >
                <DataGridComboBoxColumn.EditingElementStyle>
                    <Style TargetType="ComboBox">
                        <Setter Property="ItemsSource" Value="{Binding SectorList}" />
                    </Style>
                </DataGridComboBoxColumn.EditingElementStyle>
                <DataGridComboBoxColumn.ElementStyle>
                    <Style TargetType="ComboBox">
                        <Setter Property="ItemsSource" Value="{Binding SectorList}" />
                    </Style>
                </DataGridComboBoxColumn.ElementStyle>
            </DataGridComboBoxColumn>
        </DataGrid.Columns>
    </DataGrid>

Ответы [ 3 ]

8 голосов
/ 01 декабря 2011

Редактирование столбца DataGridComboBox для одного клика + один флажок Редактирование столбца
См. Также: https://stackoverflow.com/a/8333704/724944

XAML:

        <Style TargetType="{x:Type DataGridCell}">
            <EventSetter Event="PreviewMouseLeftButtonDown" Handler="DataGridCell_PreviewMouseLeftButtonDown" />
            <EventSetter Event="PreviewTextInput" Handler="DataGridCell_PreviewTextInput" />
        </Style>

Кодовый код:

    private void DataGridCell_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        DataGridCell cell = sender as DataGridCell;
        GridColumnFastEdit(cell, e);
    }

    private void DataGridCell_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        DataGridCell cell = sender as DataGridCell;
        GridColumnFastEdit(cell, e);
    }

    private static void GridColumnFastEdit(DataGridCell cell, RoutedEventArgs e)
    {
        if (cell == null || cell.IsEditing || cell.IsReadOnly)
            return;

        DataGrid dataGrid = FindVisualParent<DataGrid>(cell);
        if (dataGrid == null)
            return;

        if (!cell.IsFocused)
        {
            cell.Focus();
        }

        if (cell.Content is CheckBox)
        {
            if (dataGrid.SelectionUnit != DataGridSelectionUnit.FullRow)
            {
                if (!cell.IsSelected)
                    cell.IsSelected = true;
            }
            else
            {
                DataGridRow row = FindVisualParent<DataGridRow>(cell);
                if (row != null && !row.IsSelected)
                {
                    row.IsSelected = true;
                }
            }
        }
        else
        {
            ComboBox cb = cell.Content as ComboBox;
            if (cb != null)
            {
                //DataGrid dataGrid = FindVisualParent<DataGrid>(cell);
                dataGrid.BeginEdit(e);
                cell.Dispatcher.Invoke(
                 DispatcherPriority.Background,
                 new Action(delegate { }));
                cb.IsDropDownOpen = true;
            }
        }
    }


    private 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 = VisualTreeHelper.GetParent(parent) as UIElement;
        }
        return null;
    }
2 голосов
/ 24 июня 2016

У меня были проблемы с ответом @ surfen, возможно потому, что это произошло много лет спустя, и WPF, вероятно, сильно изменился. Кажется, DataGrid теперь позаботится о некоторых вещах для вас, например, об автоматическом редактировании текстового поля, когда вы начнете печатать.

Я использую DataGridTemplateColumn для своего столбца со списком. Шаблон имеет TextBlock для CellTemplate. Вызов BeginEdit с последующим вызовом диспетчера приводит к появлению поля со списком в визуальном дереве. Затем кажется, что щелчок мыши отправляется в поле со списком, и он открывается сам по себе.

Вот моя модифицированная версия кода @ surfen:

public static class DataGridExtensions
{
    public static void FastEdit(this DataGrid dataGrid)
    {
        dataGrid.ThrowIfNull(nameof(dataGrid));

        dataGrid.PreviewMouseLeftButtonDown += (sender, args) => { FastEdit(args.OriginalSource, args); };
    }

    private static void FastEdit(object source, RoutedEventArgs args)
    {
        var dataGridCell = (source as UIElement)?.FindVisualParent<DataGridCell>();

        if (dataGridCell == null || dataGridCell.IsEditing || dataGridCell.IsReadOnly)
        {
            return;
        }

        var dataGrid = dataGridCell.FindVisualParent<DataGrid>();

        if (dataGrid == null)
        {
            return;
        }

        if (!dataGridCell.IsFocused)
        {
            dataGridCell.Focus();
        }

        if (dataGridCell.Content is CheckBox)
        {
            if (dataGrid.SelectionUnit != DataGridSelectionUnit.FullRow)
            {
                if (!dataGridCell.IsSelected)
                {
                    dataGridCell.IsSelected = true;
                }
            }
            else
            {
                var dataGridRow = dataGridCell.FindVisualParent<DataGridRow>();

                if (dataGridRow != null && !dataGridRow.IsSelected)
                {
                    dataGridRow.IsSelected = true;
                }
            }
        }
        else
        {
            dataGrid.BeginEdit(args);

            dataGridCell.Dispatcher.Invoke(DispatcherPriority.Background, new Action(() => { }));
        }
    }
}

public static class UIElementExtensions
{
    public static T FindVisualParent<T>(this UIElement element)
        where T : UIElement
    {
        UIElement currentElement = element;

        while (currentElement != null)
        {
            var correctlyTyped = currentElement as T;

            if (correctlyTyped != null)
            {
                return correctlyTyped;
            }

            currentElement = VisualTreeHelper.GetParent(currentElement) as UIElement;
        }

        return null;
    }
}
1 голос
/ 17 января 2019

Ни один из других ответов не работал для меня.Что работало для меня, хотя было следующее.

<DataGridComboBoxColumn
    Header="Example ComboBox"
    DisplayMemberPath="Name"
    SelectedValuePath="Id">
    <DataGridComboBoxColumn.EditingElementStyle>
        <Style TargetType="ComboBox">
            <Setter Property="IsDropDownOpen" Value="True" />
        </Style>
    </DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>

Я не помню, где я получил это решение.Возможно, это произошло из-за переполнения стека.Если кто-то увидит первоисточник, оставьте комментарий.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...