WPF怎么让datagrid的某个cell下的模板控比如textBox,获取焦点?要光标一闪一闪的效果,便于用户输入 5
不要单纯的选中,需要光标一闪一闪的那种效果,才能方便用户输入。以下代码是获得cell的焦点(但只是选中了某个cell)inti=0;privatevoidbutton1_...
不要单纯的选中,需要光标一闪一闪的那种效果,才能方便用户输入。以下代码是获得cell的焦点(但只是选中了某个cell)
int i = 0;
private void button1_Click(object sender, RoutedEventArgs e)
{
if (i < this.dataGrid.Items.Count)
{
DataGridRow dr = (DataGridRow)this.dataGrid.ItemContainerGenerator.ContainerFromIndex(i);
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(dr);
DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(0); //取第0列每行单元格
cell.Focus();
i++;
}
else
{
i = 0;
}
public static T GetVisualChild<T>(Visual parent) where T : Visual
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
child = v as T;
if (child == null)
{
child = GetVisualChild<T>(v);
}
if (child != null)
{
break;
}
}
return child;
} 展开
int i = 0;
private void button1_Click(object sender, RoutedEventArgs e)
{
if (i < this.dataGrid.Items.Count)
{
DataGridRow dr = (DataGridRow)this.dataGrid.ItemContainerGenerator.ContainerFromIndex(i);
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(dr);
DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(0); //取第0列每行单元格
cell.Focus();
i++;
}
else
{
i = 0;
}
public static T GetVisualChild<T>(Visual parent) where T : Visual
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
child = v as T;
if (child == null)
{
child = GetVisualChild<T>(v);
}
if (child != null)
{
break;
}
}
return child;
} 展开
2个回答
展开全部
给cell内的TextBox添加 Loaded事件
XAML
<DataGridTemplateColumn Header="数量">
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding 数量}" BorderBrush="{x:Null}" Background="{x:Null}" BorderThickness="0" Loaded="TextBox_Loaded" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
cs
private void TextBox_Loaded(object sender, RoutedEventArgs e)
{
TextBox testTB = sender as TextBox;
testTB.Focus();
}
XAML
<DataGridTemplateColumn Header="数量">
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding 数量}" BorderBrush="{x:Null}" Background="{x:Null}" BorderThickness="0" Loaded="TextBox_Loaded" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
cs
private void TextBox_Loaded(object sender, RoutedEventArgs e)
{
TextBox testTB = sender as TextBox;
testTB.Focus();
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询