gpt4 book ai didi

c# - WPF Datagrid在添加新项目后进入编辑

转载 作者:行者123 更新时间:2023-12-03 10:20:08 25 4
gpt4 key购买 nike

我有一个 WPF DataGrid,它有一列,绑定(bind)到我的 ViewModel 中的 ObservableCollection。用户单击将新项目添加到列表的按钮。项目被添加到 ObservableCollection 中,并且新项目按预期显示在 DataGrid 中。

每次用户添加新项目时,我都希望将新单元格置于编辑模式,以便用户可以编辑项目名称。不确定如何使用 MVVM 模式执行此操作。

最佳答案

不幸的是,在 MVVM 中没有简单的方法可以做到这一点。模式作为 DataGridCell 上的必要属性DataGrid 中不存在和编辑模式只能通过调用方法来实现。

将解决方案的讨厌程度降至最低的方法是实现一个接口(interface),以便您的 View 中的代码针对界面工作,而不是直接与您的ViewModel 交互,至少允许某种程度的去耦。在您的 DataContextChanged 期间为您的界面附加事件处理程序您的 View 中的处理程序.

理想情况下,您的界面应该引发一个事件,然后您在 View 代码隐藏中处理该事件以调用 BeginEdit()DataGrid一旦你专注于你的特定细胞。聚焦特定单元格,开始编辑,然后聚焦现在创建的子编辑元素控件(即 TextBox )。

例如:

private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
IRaiseStartCellEditEvent context = DataContext as IRaiseStartCellEditEvent;
if (context != null)
{
context.StartCellEdit += (o, args) =>
{
//Get the cell from first row
var cell = DataGrid.GetCell(0, 2);
//Focus on the cell for editing
cell.Focus();
//Start editing the cell
DataGrid.BeginEdit();
//Get the editing textbox
var tbEditor = Extensions.GetVisualChild<TextBox>(cell);
//Force the keyboard focus
if (tbEditor != null)
{
Keyboard.Focus(tbEditor);
tbEditor.SelectAll();
}
};
}
}

关于c# - WPF Datagrid在添加新项目后进入编辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32204761/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com