我有 DataGrid 和我的类类型的 ObservableCollection 作为数据源。我正在使用一些具有相同 DataTemplate 的 TemplateColumns,所以我想到我为该列创建类。 问题是我不知道在那种情况下如何绑定数据。
我的类显然扩展了 DataGridTemplateColumn 公共类 WindowedColumn:DataGridTemplateColumn
我还有属性
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(Binding), typeof(WindowedColumn), new PropertyMetadata(null));
public static readonly DependencyProperty MaxLengthProperty =
DependencyProperty.Register("MaxLength", typeof(Binding), typeof(WindowedColumn), new PropertyMetadata(null));
public Binding Text
{
get { return (Binding)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public Binding MaxLength
{
get { return (Binding)GetValue(MaxLengthProperty); }
set { SetValue(MaxLengthProperty, value); }
}
我的构造函数代码:
BindingOperations.SetBinding(this, FrameworkElement.DataContextProperty, new Binding
{
RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(DataGrid), 1)
});
var standardTemplate = new DataTemplate();
var standardTextBlock = new FrameworkElementFactory(typeof(TextBlock));
standardTextBlock.SetBinding(TextBlock.TextProperty, Text);
standardTemplate.VisualTree = standardTextBlock;
DataTemplate editingTemplate = new DataTemplate();
var editingStackPanel = new FrameworkElementFactory(typeof(StackPanel));
editingStackPanel.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
var editingTextBox = new FrameworkElementFactory(typeof(TextBox));
editingTextBox.SetBinding(TextBox.TextProperty, Text);
//editingTextBox.SetBinding(TextBox.MaxLengthProperty, MaxLength);
editingTextBox.SetValue(TextBox.MinWidthProperty, 50.0);
editingTextBox.SetValue(TextBox.MaxWidthProperty, 200.0);
var editingButton = new FrameworkElementFactory(typeof(Button));
editingButton.SetValue(ContentControl.ContentProperty, ":");
editingStackPanel.AppendChild(editingTextBox);
editingStackPanel.AppendChild(editingButton);
editingTemplate.VisualTree = editingStackPanel;
CellTemplate = standardTemplate;
CellEditingTemplate = editingTemplate;
在我的 xaml 文件中,我这样使用它
<Columns:WindowedColumn Header="My Column" Text="{Binding OrderNumber}" MaxLength="{Binding MyMaxLengthProperty}"/>
Visual 在 xaml 中显示没有找到 OrderNumber 的 dataContext,当然,当我运行程序时,我没有看到我在其他具有相同测试绑定的 TextColumn 中看到的任何值