【发布时间】:2019-03-08 04:11:02
【问题描述】:
我有一个带有数据网格的 WPF 应用程序,我将其绑定到我的 ViewModel 中的自定义 LINQ to SQL 查询,该查询将来自两个不同表的列汇集在一起:
public ICollectionView SetsView { get; set; }
public void UpdateSetsView()
{
var sets = (from s in dbContext.Sets
join o in dbContext.SetParts on s.ID equals o.SetID into g1
select new
{
s.ID,
s.SetNumber,
s.SetTitle,
s.SetType,
s.SetNotes,
s.SetUrl,
s.HaveAllParts,
s.NumberOfSets,
s.IsBuilt,
s.DateAdded,
s.LastModified,
UniqueParts = g1.Count(),
TotalParts = g1.Sum(o => o.Quantity)
}
);
SetsView = CollectionViewSource.GetDefaultView(sets);
}
SetsView 集合绑定到我的数据网格,因为我需要能够编辑任何行的 SetNotes 的值并将其保存回数据库中的 Sets 表,所以我为 CellEditEnding 添加了一个事件处理程序( CellEditEnding="dgST_Sets_CellEditEnding ") 到 DataGrid 定义并创建此列:
<DataGridTemplateColumn Header="Set Notes"
SortMemberPath="SetNotes"
Width="*">
<DataGridTemplateColumn.HeaderStyle>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="HorizontalContentAlignment" Value="Center"/>
</Style>
</DataGridTemplateColumn.HeaderStyle>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding SetNotes, Mode=OneWay}" Margin="5,0,5,0"
HorizontalAlignment="Stretch" VerticalAlignment="Center" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding SetNotes, Mode=OneWay}" Margin="5,0,5,0"
HorizontalAlignment="Stretch" VerticalAlignment="Center"
/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
问题是,当我运行应用程序并编辑任何行中的 Set Notes 列时,我无法弄清楚如何从事件 args 中获取已编辑单元格的新值。我以为我可以将事件 args EditingElement 实例强制转换为 TextBox(请参阅下面的处理程序),但是当我运行应用程序时,编辑一行并更改 SetNotes 的值,EditingElement 的类型是 ContentPresenter 而不是 TextBox,我可以不知道如何获取更改后的值。
private void dgST_Sets_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
string newValue = ((TextBox)e.EditingElement).Text;
//Code here to update table
}
请记住,我正在绑定到自定义 LINQ to SQL 查询,因此这不是典型的模型绑定问题。另请注意,在我的模板列中绑定 SetNotes 的值时,我别无选择,但使用 Mode=OneWay 作为使用任何其他选项会给我访问只读属性时出现运行时错误 - 这可能是问题吗?
我已经为此花费了几个小时,并且毫无乐趣地无休止地搜索 - 谁能帮帮我吗?
【问题讨论】:
标签: wpf data-binding linq-to-sql wpfdatagrid