//System.InvalidOperationException:“双向绑定需要 Path 或 XPath。”
//在按下界面的datagrid控件时触发绑定的列内容,然后出现此异常
//没有用到SQL数据库,单纯以文本的形式拖拽
//目前参考微软官网WPF发现有动态绑定的信息ObservableCollection
//找到一处感觉会有效的文章 Addr:https://www.cnblogs.com/lonelyxmas/p/3510551.html
//整理一下,问题解决了
//第一步使用datagrid的CellEditEnding控件和BeginningEdit控件,出处:https://docs.microsoft.com/zh-cn/dotnet/api/system.windows.controls.datagrid.celleditending?view=netcore-3.1
XAML: <DataGrid Height="86" VerticalAlignment="Top" Width="628" ItemsSource="{Binding DishMenus}" AutoGenerateColumns="False" GridLinesVisibility="None" Grid.Row="1" CellEditEnding="dataGrid_CellEditEnding" BeginningEdit="dataGrid_BeginningEdit">
//第二步在cs文件下添加事件
XAML.cs:
private void dataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
set_Form_.CellEditEnding((e.EditingElement as System.Windows.Controls.TextBox).Text);
}
private void dataGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
{
set_Form_.BeginningEdit((e.Column.GetCellContent(e.Row) as TextBlock).Text);
}
//第三步在 ViewModel层去处理这些事件
static string sTrDataGrid = "";
public void BeginningEdit(string select)
{
//将修改前的值保存起来
preValue = select;
}
public void CellEditEnding(string select)
{
string newValue = select;
if (sTrDataGrid != newValue)
{
Data_Service xds = new Data_Service();
List<Name_DataGrid> dishList = xds.getAllNames();
foreach (Name_DataGrid d in dishList)
{
if (d.Name == preValue)
{
var model = dishList.Where(c => c.Name == d.Name).FirstOrDefault();
model.Name = newValue;
xds.setAllName(dishList);
}
}
}
}
//结束,只要肯变强,就不会成为被饿死的徒弟。