Mvvm 将焦点放在行选择上wpf datagrid中的特定可编辑datagrid单元格
我在datagrid中有四列,第四列是模板化的,有文本框,它总是可编辑的 我在这里试图实现的是,当行选择更改高亮显示行的第四个单元格时,该单元格是可编辑的,并且其中包含文本框,因此应获得焦点 我可以在codebehind或xaml中完成这项工作 以下是我所做的:Mvvm 将焦点放在行选择上wpf datagrid中的特定可编辑datagrid单元格,mvvm,datagrid,wpf-controls,wpf-4.5,Mvvm,Datagrid,Wpf Controls,Wpf 4.5,我在datagrid中有四列,第四列是模板化的,有文本框,它总是可编辑的 我在这里试图实现的是,当行选择更改高亮显示行的第四个单元格时,该单元格是可编辑的,并且其中包含文本框,因此应获得焦点 我可以在codebehind或xaml中完成这项工作 以下是我所做的: <DataGrid Name="MyGrid" SelectionChanged="MyGrid_OnSelectionChanged" AutoGenerateColumns="False"> <Da
<DataGrid Name="MyGrid" SelectionChanged="MyGrid_OnSelectionChanged" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Str1}" IsReadOnly="True"/>
<DataGridTextColumn Binding="{Binding Str2}" IsReadOnly="True"/>
<DataGridTextColumn Binding="{Binding Str3}" IsReadOnly="True"/>
<DataGridTemplateColumn >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Str4}" GotFocus="UIElement_OnGotFocus" >
<TextBox.Style >
<Style TargetType="TextBox">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=DataGridCell,AncestorLevel=1},Path=IsSelected}">
<Setter Property="FocusManager.FocusedElement" Value="{Binding RelativeSource={RelativeSource Self}}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
private void PopulateDummies()
{
int i = 0;
List<SomeDummy> dummies = new List<SomeDummy>();
while (i < 10)
{
dummies.Add(new SomeDummy
{
Str1 = string.Format("Str1:{0}", i),
Str2 = string.Format("Str2:{0}", i),
Str3 = string.Format("Str3:{0}", i),
Str4 = string.Format("Str4:{0}", i)
});
i++;
}
MyGrid.ItemsSource = dummies;
}
private void MyGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void UIElement_OnGotFocus(object sender, RoutedEventArgs e)
{
var txtB = sender as TextBox;
txtB.Focus();
txtB.SelectAll();
}
私有void填充摘要()
{
int i=0;
列表假人=新列表();
而(i<10)
{
虚拟对象。添加(新的虚拟对象)
{
Str1=string.Format(“Str1:{0}”,i),
Str2=string.Format(“Str2:{0}”,i),
Str3=string.Format(“Str3:{0}”,i),
Str4=string.Format(“Str4:{0}”,i)
});
i++;
}
MyGrid.ItemsSource=假人;
}
私有void MyGrid_OnSelectionChanged(对象发送方,SelectionChangedEventArgs e)
{
}
私有void UIElement_OnGotFocus(对象发送方、路由目标方)
{
var txtB=发送方作为文本框;
txtB.Focus();
txtB.SelectAll();
}
似乎什么都不管用。不知道原因是什么。有人能帮忙吗
txtB.Focus();
用TextEditory控件有效地替换DataGridCell。为此,需要更新视图,因此需要运行UI。
在创建编辑器之前,SelectAll无法运行,因此请将其作为单独的调度程序作业运行,并替换为以下内容:
Application.Current.Dispatcher.BeginInvoke(new Action(() => {
txtB.SelectAll();
}), DispatcherPriority.Render);
这就可以了,您不需要SelectChanged事件处理程序来实现此目的。这是出乎意料的:我创建了一个新的WPF应用程序,将代码放在MainWindow.xaml中,并用我的建议替换了语句txtB.SelectAll()。单击单元格(第4列)设置行选择,将焦点放在编辑器单元格上,现在所有文本也被选中。也许我不明白你想要实现什么。