我正在尝试提供一个行为类似于DataGridTextColumn的DataGrid列,但在编辑模式下有一个额外的按钮。我查看了DataGridTemplateColumn,但似乎更容易将DataGridTextColumn子类化,如下所示
问题是textBox在添加到网格时失去了绑定。也就是说,对其文本属性的更改不会反映在非编辑TextBlock或基础视图模式中
有没有想过为什么会发生这种情况,以及我如何解决这个问题?
public class DataGridFileColumn : DataGridTextColumn
{
protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem)
{
TextBox textBox = (TextBox)base.GenerateEditingElement(cell, dataItem);
Button button = new Button { Content = "..." };
Grid.SetColumn(button, 1);
return new Grid
{
ColumnDefinitions = {
new ColumnDefinition(),
new ColumnDefinition { Width = GridLength.Auto },
},
Children = {
textBox,
button,
},
};
}
}我使用的是WPF3.5和.NET工具包
发布于 2011-08-30 22:59:13
事实证明,您还需要覆盖PrepareCellForEdit、CommitCellEdit和CancelCellEdit
基类假定(并非没有道理)传入的FrameworkElement将是一个TextBox
发布于 2011-08-30 21:51:45
我认为您必须在GenerateEditingElement中手动设置绑定(...)方法。
从基类获取TextBox后,如下所示设置它的绑定:
textBox.DataContext = dataItem;
textBox.SetBinding(TextBlock.TextProperty, Binding);不管怎样,这对我来说是有效的。
注意,我不确定为什么这样做,因为阅读GenerateEditingCell的文档对我来说意味着您从基类获取的TextBox应该已经正确地设置了它的绑定。然而,上面的方法就是他们所做的in this blog post。
编辑:
您实际上不需要设置绑定,它已经完成了(正如文档中所说的那样)。但是,您确实需要设置DataContext,因为出于某种原因,它没有在从基类返回的textBox上设置。
https://stackoverflow.com/questions/7243235
复制相似问题