Xamly set keyboard focus to an element in DataGridTemplateColumn cell?

安稳与你 提交于 2019-12-24 04:52:11

问题


I've set stuff in a DataGridTemplateColumn.CellEditing DataTemplate. I want that when the cell editing loads and shows the template, keyboard-focus should be given to a certain control in the template.

Consider this example, when you go edit mode, the textbox is not keyboard-focused:

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
    <Grid>
    <DataGrid Name="dg" AutoGenerateColumns="False">
      <DataGrid.Columns>
        <DataGridTemplateColumn Header="Title">
          <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
              <TextBlock Text="{Binding Title}"/>
            </DataTemplate>
          </DataGridTemplateColumn.CellTemplate>
          <DataGridTemplateColumn.CellEditingTemplate>
            <DataTemplate>
              <TextBox Text="{Binding Title}"/>
            </DataTemplate>
          </DataGridTemplateColumn.CellEditingTemplate>
        </DataGridTemplateColumn>
        <DataGridTemplateColumn Header="Value">
          <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
              <TextBlock Text="{Binding Note}"/>
            </DataTemplate>
          </DataGridTemplateColumn.CellTemplate>
          <DataGridTemplateColumn.CellEditingTemplate>
            <DataTemplate>
              <TextBox Text="{Binding Note}"/>
            </DataTemplate>
          </DataGridTemplateColumn.CellEditingTemplate>
        </DataGridTemplateColumn>
      </DataGrid.Columns>      
    </DataGrid>
  </Grid>
</Window>

Class MainWindow 

  Private Sub Window_Loaded(ByVal sender As Object,
                            ByVal e As RoutedEventArgs) Handles MyBase.Loaded

    Dim data As New List(Of Item) From
      {New Item,
       New Item,
       New Item}
    dg.ItemsSource = data
  End Sub

End Class

Public Class Item
  Private Shared Number As Integer = 0
  Sub New()
    Number += 1
  End Sub
  Public Property Title = "Title " & Number.ToString
  Public Property Note = "Note " & Number.ToString
End Class

回答1:


Well answer was actually simple, the above textboxes should be changed as follows:

<TextBox Text="{Binding Title}"
  FocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}"/>
<TextBox Text="{Binding Note}"
  FocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}"/>


来源:https://stackoverflow.com/questions/4218718/xamly-set-keyboard-focus-to-an-element-in-datagridtemplatecolumn-cell

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