wpf - WPF MVVM 中 DataGrid DataTemplate 组合框中的 IsDropDownOpen

标签 wpf xaml mvvm datagrid combobox

我有一个 DataGrid,其中 DataTemplate 中有一个 ComboBox

<DataGridTemplateColumn Header="Stock Name" Width="290">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding StockName}"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    <DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>
            <ComboBox Width="290" Name="cmbStock" ItemsSource="{Binding Path=Stocks}" FocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}" ></ComboBox>
        </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>

当我使用 Tab 到达此 DataGridCell 时,我希望 ComboBox 能够 DropDownOpen 这包括当我到达 DataGrid 单元格时使其处于编辑模式。

我正在使用 WPF MVVM

最佳答案

我认为您需要做的是强制数据网格进入“单击或选项卡”编辑模式。基本上,当单元格聚焦时,强制网格将 CellTemplate 切换为 CellEditingTemplate。其代码是:

BeginEdit(); //dataGrid.BeginEdit()

现在如何以及在何处连接它取决于您想要做多少工作。您可以扩展 DataGrid 类并引入 DependencyProperty“SingleClickEdit”或任何您想要的名称。然后,当按下监视器/预览键并在选项卡上选择单元格并强制其处于编辑模式时。或者,如果您只需要该列,您可以只监视:

<TextBlock Text="{Binding StockName}" 
           GotFocus="OnGotFocus" 
           PreviewKeyDown="OnPreviewKeyDown"
  ....., or something like that

然后在 .cs 代码中,例如在 OnGotFocus() 中,调用 datagrid.BeginEdit()。

编辑:(根据下面的评论/对话)

  • 将 SelectionChanged 处理程序添加到数据网格
  • 将 IsDropDownOpen = true 添加到组合框

    <DataGrid x:Name="dataGrid" 
           SelectionChanged="dataGrid_SelectionChanged"
           ....>
    
    <ComboBox Width="290" Name="cmbStock" ItemsSource="{Binding Path=Stocks}" 
          ...
          IsDropDownOpen="True"></ComboBox>
    </DataTemplate>
    
  • 在 .cs 中

    private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        dataGrid.BeginEdit();
    }
    

这应该可以,在我的测试中工作:),基本上你是在选择时强制数据网格进入编辑模式,并且在编辑模式下,你得到了已经打开的组合框

关于wpf - WPF MVVM 中 DataGrid DataTemplate 组合框中的 IsDropDownOpen,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10285609/

相关文章:

c# - 如何使用 ObservableCollection 从 ViewModel 刷新 UI?

wpf - Blend/WPF 中按钮上的蓝色鼠标悬停效果

c# - 创建全局集合并从所有页面访问它 (C# Windows)

c# - WPF 自定义控件(多选组合框)的问题

c# - 如何检测 ScrollViewer 何时完成滚动?

javascript - 如何在Sitecore中构建SPEAK组件?

wpf - View 未更新 (MVVM),但相关属性已正确更新

c# - 强制窗口在打开时获得焦点

c# - 等待异步方法而不阻塞线程

c# - 限制每秒绑定(bind)更新