【问题标题】:How to create a IList Dep property in DataGridTextColumn custom control如何在 DataGridTextColumn 自定义控件中创建 IList Dep 属性
【发布时间】:2018-12-20 03:55:59
【问题描述】:

我想将一个列表对象传递给我的数据网格 DataGridTextColumn 的自定义控件。 为此我使用了这段代码

public class DataGridListBoxColumn : DataGridTextColumn
{
public IList<Student> ListItems
{
get { return (IList<Student>)GetValue(_ListItems); }
set { SetValue(_ListItems, value); }
}
public static readonly DependencyProperty _ListItems = DependencyProperty.Register("ListItems", typeof(IList<Student>), typeof(DataGridListBoxColumn));  
}

我的 XAML

 <local:DataGridListBoxColumn   Binding="{Binding M_Name,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" ListItems="{Binding Path= stud, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MainWindow}}}"  Width="100"/>

<local:DataGridListBoxColumn   Binding="{Binding M_Name,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" ListItems="{Binding RelativeSource={RelativeSource AncestorType=DataGridTextColumn}, Path=stud}"  Width="100"/>

两者都不起作用,有什么方法可以将列表传递给我的自定义控件 谢谢

【问题讨论】:

  • stud在哪里?
  • @Rekshino 对不起,但你是对的。似乎我不明白 XAML 解析器如何处理绑定...... OP 仍应遵守此命名约定。我确信我见过由于错误命名的标识符字段而导致绑定不起作用的情况。
  • @Clemens 没问题! :) 正如我所说,这是我的第一个猜测,你是对的,该约定是命名 abcProperty

标签: wpf custom-controls dependency-properties listobject


【解决方案1】:

DataGrid 列的问题在于,它们不存在于可视化或逻辑树中,因此您不能使用RelativeSource。也有限制的可能性是为您的绑定设置Source x:Reference。限制是,您不能将其设置为源 UIElement,其中包含具有绑定的元素。因此,您不能设置包含列作为绑定源的主窗口或数据网格,否则您将获得循环依赖。
现在在您的 DataGrid 旁边放置一个隐藏控件作为对数据的访问,或者使用一些现有的:

<TextBlock x:Name="studAccess" Visibility="Collapsed"/>
<DataGrid>
<local:DataGridListBoxColumn .../>
</DataGrid>

并通过此控件绑定列的依赖属性(暗示studAccessDataContext 具有stud 属性):

<local:DataGridListBoxColumn   Binding="{Binding M_Name,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" ListItems="{Binding DataContext.stud, Source={x:Reference studAccess}}"  Width="100"/>

【讨论】:

  • 我添加了一个 TextBlock 并按照您的说明进行绑定,但我在 Listitem 属性中得到了 null。stud 是 Vm 中的列表对象。我已经像上面那样编辑了我的代码。谢谢
  • protected override FrameworkElement GenerateEditingElement(DataGridCell cell, Object dataItem) { textBox = (TextBox)base.GenerateEditingElement(cell, dataItem); textBox.TextChanged += TextBox_TextChanged;绑定 b = 新绑定(); b.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(DataGridListBoxColumn), 1); b.Path = new PropertyPath("ListItem"); tx.SetBinding(TextBlock.TextProperty, b);返回文本框; }
  • 我绑定到一个文本块,我在列表项中得到空值。
  • @babucr 不要在DataGrid 中创建TextBlock。我已经编辑了我的回答,因为它对你来说更清楚。
猜你喜欢
  • 2020-12-24
  • 2011-06-20
  • 2011-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多