【问题标题】:DataContext changes not always causing binding updates on class from DataTemplate.LoadContentDataContext 更改并不总是导致 DataTemplate.LoadContent 类的绑定更新
【发布时间】:2011-03-08 18:26:06
【问题描述】:

我正在创建一些附加属性,其中之一是 DataTemplate。 DataTemplate 应该有一个我在其中定义的 FrameworkElement,以便所有这些的 XAML 声明如下所示:

<SomeControl m:ItemsSource="{Binding Source}">
  <m:MyTemplate>
    <DataTemplate>
      <m:MyClass SomeDependency="{Binding Path}"/>
    </DataTemplate>
  </m:MyTemplate>
</SomeControl>

在 MyTemplateProperty 更改回调的代码中,它遍历 Source 中的每个项目并调用 DataTemplate 上的 LoadContent()。然后它将 LoadContent() 返回的类上的 DataContext 设置为 Source 中的项目:

private static void MyTemplateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
  var items = (d as SomeControl).GetValue(ItemsSourceProperty) as IList;
  var template = e.NewValue as DataTemplate;
  foreach(var item in items)
  {
    var myClass = template.LoadContent() as MyClass;
    myClass.DataContext = item;
  }
}

这里奇怪的是,以这种方式创建的第一个 MyClass 实例获得了绑定更新(SomeDependencyProperty 使用来自 ItemsSource 的项目中的值更新),但其余实例都没有更新。

我已经通过自己创建 MyClass 而不是 LoadContent 调用并使用 BindingOperation.SetBinding 设置绑定来验证这应该可以正常工作,例如:

foreach(var item in items)
{
  var myClass = new MyClass();
  BindingOperations.SetBinding(myClass, MyClass.SomeDependencyProperty, new Binding("Path");
  myClass.DataContext = item;
}

有谁知道为什么 LoadContent 调用似乎会生成在 DataContext 更改时不会全部更新其绑定的对象? LoadContent 调用与自己创建对象有何不同?

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    一位同事指出,MyClass 的实例没有任何保留。添加引用这些实例的方法解决了我看到的问题。它并不能完全解释为什么第一个实例会获得更新而其他实例不会,但它解决了我的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-18
      • 2013-06-15
      • 1970-01-01
      • 2019-10-04
      • 1970-01-01
      • 2013-07-07
      • 1970-01-01
      • 2023-03-26
      相关资源
      最近更新 更多