类型为“Binding”的DependencyProperty没有被更新

4

我在创建类型为"Binding"的DependencyProperty时遇到了问题。其他类型可以正常使用,如果我使用绑定填充它们,则可以成功解析。

在我的场景中,我想获取原始绑定,以便可以将其用于绑定到子对象的属性,就像DataGrid对列所做的那样 - 即对于在列中指定的每个绑定,它会绑定到ItemsSource集合中的每个项,而不是绑定到DataContext本身。

<mg:MultiSelectDataGrid x:Name="Grid" DockPanel.Dock="Left" 
     ItemsSource="{Binding Path=Rows}" DataContext="{Binding}" 
     AutoGenerateColumns="False" UriBinding="{Binding Path=UrlItems}">

在我的“MultiSelectDataGrid”中:

    public static readonly DependencyProperty UriBindingProperty = 
       DependencyProperty.Register("UriBinding", typeof(BindingBase),
           typeof(MultiSelectDataGrid), 
           new PropertyMetadata { PropertyChangedCallback = OnBindingChanged});


    private static void OnBindingChanged(DependencyObject d,
                            DependencyPropertyChangedEventArgs e)
    {
         // This is never enterred
    }


    public BindingBase UriBinding
    {
        get { return (BindingBase)GetValue(UriBindingProperty); }
        set { SetValue(UriBindingProperty, value); }
    }

回调函数从未被调用,属性也从未被设置。我尝试了各种排列组合,有回调函数,没有回调函数。唯一让我取得任何成功的是,如果我用一个字符串替换绑定(例如UriBinding="hello")——在那种情况下它会触发回调函数,并设置属性,但当然会失败,因为它是错误的类型。

我做错了什么?我看到了很多这样的例子,我想这就是DataGrid必须要做的。

谢谢

2个回答

8
有趣的是,我所知道的唯一具有 Binding 类型属性的其他地方是 DataGridBoundColumn 类,该类派生到 DataGridTextColumn、DataGridCheckBoxColumn 等等...

有趣的是,在那里,该属性不是依赖属性。它是一个普通的 CLR 类型属性。我猜绑定基础设施是基于这样一个限制:您不能将绑定类型 DP 绑定。

该类的其他属性非常好,例如 Visibility、Header 等都是依赖属性。

在 DataGridBoundColumn 中,Binding 属性的声明如下,并附有对其的简要解释...

这不是 DP,因为如果是,则获取值将评估绑定。

    /// <summary>
    ///     The binding that will be applied to the generated element.
    /// </summary>
    /// <remarks>
    ///     This isn't a DP because if it were getting the value would evaluate the binding.
    /// </remarks>
    public virtual BindingBase Binding
    {
        get
        {
            if (!_bindingEnsured)
            {
                if (!IsReadOnly)
                {
                    DataGridHelper.EnsureTwoWayIfNotOneWay(_binding);
                }

                _bindingEnsured = true;
            }

            return _binding;
        }

        set
        {
            if (_binding != value)
            {
                BindingBase oldBinding = _binding;
                _binding = value;
                CoerceValue(IsReadOnlyProperty);
                CoerceValue(SortMemberPathProperty);
                _bindingEnsured = false;
                OnBindingChanged(oldBinding, _binding);
            }
        }
    }

3

虽然@WPF-it的解决方案可行,但对于附加属性来说并不适用,因为您无法附加CLR属性。要解决这个问题,您可以像往常一样定义您的附加属性,并通过调用BindingOperations.GetBindingBase()方法获取绑定对象。

private static void OnMyPropChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    // Can also use GetBinding(), GetBindingExpression()
    // GetBindingExpressionBase() as needed.
    var binding = BindingOperations.GetBindingBase(d, e.Property);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接