[英]Get focus on a ComboBox in DataGrid with tab key
我在DataGridTemplateColumn中有一個ComboBox:
<DataGrid x:Name="dataVoitures" Grid.Row="0" AutoGenerateColumns="False" ItemsSource="{Binding ListBagnoles}"
CanUserAddRows="False">
<DataGrid.Columns>
...
<DataGridTemplateColumn Header="Carburant" SortMemberPath="Carburant.NomCarburant">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Carburant.NomCarburant}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox x:Name="comboCarbu" ItemsSource="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}},
Path=DataContext.ListeCarburants}"
SelectedItem="{Binding Carburant, UpdateSourceTrigger=PropertyChanged}"
DisplayMemberPath="NomCarburant" IsDropDownOpen="True" Initialized="comboCarbu_Initialized"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
...
</DataGrid.Columns>
問題是,當我在Datagrid中添加新行時,無法使用鍵盤從組合框中選擇一個項目。
通過調試,我發現使用Key Tab進入ComboBox單元時,不會觸發ComboBox.GotFocus。
我嘗試強制ComboBox在初始化Combobox時獲得焦點,但無法在oO后面的代碼中訪問組合框。
希望你能幫我 :)
我使用這篇文章找到了自己的方法: 在代碼背后的DataTemplate中找到WPF元素
我只是將FindVisualChildren方法添加到類中,並在觸發ComboBox_Initialized處理程序時將焦點強制到組合框:
private void comboCarbu_Initialized(object sender, EventArgs e)
{
foreach (var combobox in FindVisualChildren<ComboBox>(dataVoitures))
{
if (combobox.Name == "comboCarbu")
{
combobox.Focus();
}
}
}
現在,我可以使用組合鍵從組合框中選擇一個項目:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.