【问题标题】:Attached Property and Binding附加属性和绑定
【发布时间】:2010-02-07 10:27:32
【问题描述】:

我正在创建附加行为以设置类的常规属性:

public class LookupHelper
{
    public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.RegisterAttached("ItemsSource", typeof(object), typeof(LookupHelper), new UIPropertyMetadata(null, OnItemsSourceChanged));

    private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var control = d as MyControl;
        if(control == null)
                return;

        control.ItemsSource = (IEnumerable)e.NewValue;
    }

    public static object GetItemsSource(GridColumn column)
    {
        return column.GetValue(ItemsSourceProperty);
    }

    public static void SetItemsSource(GridColumn column, object value)
    {
        column.SetValue(ItemsSourceProperty, value);
    }
}   

这里,MyControl 上的 ItemsSource 属性是一个常规属性,所以我无法在 Xaml 中绑定它,因此会出现这种附加行为。

现在,当我使用字符串或对象使用此附加属性时,它可以工作并且我设置的断点被命中,但是当我使用绑定标记设置它时,它永远不会运行。为什么这不起作用?

<MyControl ctrl:LookupHelper.ItemsSource="DataSource"/>; //It works
<MyControl ctrl:LookupHelper.ItemsSource="{Binding Path=MyDataSource}"/>; //Does not work

我需要做的是将 ItemsSource 属性设置为 Binding 指定的值。

【问题讨论】:

  • 你在哪里设置断点?您认为应该调用的方法/行没有被调用?
  • 您是否尝试过使用Binding 的Source 属性而不是Path? (您需要将来源指定为StaticResource)

标签: wpf binding attached-properties attachedbehaviors


【解决方案1】:

在您的 Get 和 Set 方法中,您将接收对象定义为 GridColumn,它应该是 DependencyObject。

您可能还希望将 DP 的类型从 object 更改为 IEnumerable,因为您在更改处理程序中进行了转换。

【讨论】:

    【解决方案2】:

    能否请您发布您正在使用的标记?此外,如果实际属性存在于对象上并且在那里有意义,那么我认为您应该在该对象上使用常规依赖属性,而不是在辅助类上使用附加属性。

    编辑 来自 MSDN: GetPropertyName 访问器的签名必须是:

    public static object GetPropertyName(object target)
    

    并且 SetPropertyName 访问器的签名必须是:

    public static void SetPropertyName(object target, object value)
    

    在您的情况下,GridColumn 是正确的目标类型吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-02
      • 2011-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-25
      • 2011-11-01
      • 2011-02-14
      相关资源
      最近更新 更多