在XAML中动态评估Silverlight中的绑定路径

时间:2015-05-17 23:25:51

标签: silverlight data-binding silverlight-5.0

如何动态评估绑定路径,即实际路径来自属性?例如,假设我有一个DisplayMemberPath属性,我希望有类似的东西:

Content="{Binding Path=(DisplayMemberPath)}"

我知道这不起作用,只是为了解释我想要的东西。 我知道如何通过代码构建自定义DataTemplate并动态设置它,但这不是我想要的。

1 个答案:

答案 0 :(得分:2)

您可以使用自定义行为:

<SomeControl>
    <Interaction.Behaviors>
        <DynamicBindingBehavior TargetProperty="Content"
            BindingPath="{Binding DisplayMemberPath}"/>
    </Interaction.Behaviors>
    ...
</SomeControl>

和代码:

public class DynamicBindingBehavior : Behavior<DependencyObject>
{
    private string m_targetProperty;
    public string TargetProperty
    {
        get { return m_targetProperty; }
        set
        {
            m_targetProperty = value;
            TryFindTargetProperty();
        }
    }

    private DependencyProperty m_targetDependencyProperty;

    private void TryFindTargetProperty()
    {
        if (m_targetProperty == null || AssociatedObject == null)
        {
            m_targetDependencyProperty = null;
        }
        else
        {
            var targetDependencyPropertyInfo = AssociatedObject.GetType()
                .GetProperty( TargetProperty + "Property", typeof( DependencyProperty ) );
            m_targetDependencyProperty =
                (DependencyProperty) targetDependencyPropertyInfo.GetValue(
                AssociatedObject, null );
        }
    }

    public string BindingPath
    {
        get { return (string) GetValue( BindingPathProperty ); }
        set { SetValue( BindingPathProperty, value ); }
    }

    public static readonly DependencyProperty BindingPathProperty =
        DependencyProperty.Register( "BindingPath", typeof( string ),
        typeof( DynamicBindingBehavior ),
        new PropertyMetadata( BindingPathChanged ) );

    private static void BindingPathChanged(DependencyObject d,
        DependencyPropertyChangedEventArgs e)
    {
        ((DynamicBindingBehavior) d).BindingPathChanged();
    }

    private void BindingPathChanged()
    {
        if (m_targetDependencyProperty == null) return;

        if (BindingPath == null)
        {
            AssociatedObject.ClearValue(m_targetDependencyProperty);
        }
        else
        {
            BindingOperations.SetBinding( AssociatedObject,
                m_targetDependencyProperty, new Binding( BindingPath ) );
        }
    }

    protected override void OnAttached()
    {
        base.OnAttached();
        TryFindTargetProperty();
    }

    protected override void OnDetaching()
    {
        if (m_targetDependencyProperty != null)
            AssociatedObject.ClearValue( m_targetDependencyProperty );

        base.OnDetaching();
        m_targetDependencyProperty = null;
    }
}