WPF编辑自动生成的列标题文本
我正在使用WPFWPF编辑自动生成的列标题文本,wpf,datagridview,Wpf,Datagridview,我正在使用WPFDataGrid来显示DataTable。 我需要能够编辑这个绑定的数据表(双向绑定) 我正在使用DataGrid,如下所示: <DataGrid SelectionUnit="CellOrRowHeader" IsReadOnly="False" AutoGenerateColumns="True" ItemsSource="{Binding Path=SelectedItem.BindableCont
DataGrid
来显示DataTable
。
我需要能够编辑这个绑定的数据表(双向绑定)
我正在使用DataGrid,如下所示:
<DataGrid SelectionUnit="CellOrRowHeader" IsReadOnly="False" AutoGenerateColumns="True" ItemsSource="{Binding Path=SelectedItem.BindableContent, FallbackValue={x:Null}}" />
但是我无法正确设置绑定,如果我编辑文本框中的文本,它不会更改
列.Header
-属性中的文本(这是通过绑定到数据表
自动生成的,如上所述).您忘记设置绑定的源,并且在注册绑定后不能设置值。正确的代码如下所示:
private void asdf_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
DataTemplate dt = new DataTemplate(typeof(TextBox));
e.Column.HeaderTemplate = dt;
FrameworkElementFactory txtElement =
new FrameworkElementFactory(typeof(TextBox));
dt.VisualTree = txtElement;
Binding bind = new Binding();
bind.Path = new PropertyPath("Header");
bind.Mode = BindingMode.TwoWay;
// set source here
bind.Source = e.Column;
txtElement.SetBinding(TextBox.TextProperty, bind);
// You mustn't set the value here, otherwise the binding doesn't work
// txtElement.SetValue(TextBox.TextProperty, e.Column.Header);
}
此外,您必须将绑定属性更改为
标题
,因为您正在将绑定添加到文本框的文本属性 感谢您提出的解决方案,但是绑定文本的行为是相同的,DataGrid
现在显示文本,但是当我编辑文本框中的文本时,它不会更新DataTable
(GridView的DataContext)中的文本。
private void asdf_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
DataTemplate dt = new DataTemplate(typeof(TextBox));
e.Column.HeaderTemplate = dt;
FrameworkElementFactory txtElement =
new FrameworkElementFactory(typeof(TextBox));
dt.VisualTree = txtElement;
Binding bind = new Binding();
bind.Path = new PropertyPath("Header");
bind.Mode = BindingMode.TwoWay;
// set source here
bind.Source = e.Column;
txtElement.SetBinding(TextBox.TextProperty, bind);
// You mustn't set the value here, otherwise the binding doesn't work
// txtElement.SetValue(TextBox.TextProperty, e.Column.Header);
}