wpf - 绑定(bind)一个绑定(bind)的路径属性

标签 wpf silverlight data-binding binding path

是否可以将绑定(bind)的 Path 属性绑定(bind)到另一个属性?

我想实现这段代码:

Text="{Binding Path={Binding Path=CurrentPath}}"

所以我可以动态调整我的实际绑定(bind)所引用的属性。

感谢您的帮助
强尼

最佳答案

我自己解决了。

这是解决方案,我希望它可以帮助任何像我一样遇到同样问题的人。

public class CustomBindingBehavior : Behavior<FrameworkElement>
{
    public bool IsBinding
    {
        get
        {
            return (bool)GetValue(IsBindingProperty);

        }
        set
        {
            SetValue(IsBindingProperty, value);
        }
    }

    public string PropertyPath
    {
        get
        {
            return (string)GetValue(PropertyPathProperty);

        }
        set
        {
            SetValue(PropertyPathProperty, value);
        }
    }

    public static DependencyProperty
        PropertyPathProperty = DependencyProperty.Register("PropertyPath", typeof(string),
                        typeof(CustomBindingBehavior), null);

    public static DependencyProperty
        IsBindingProperty = DependencyProperty.Register("IsBinding", typeof(bool),
                        typeof(CustomBindingBehavior), null);

    protected override void OnAttached()
    {
        if (AssociatedObject is TextBlock)
        {
            var tb = AssociatedObject as TextBlock;
            tb.Loaded += new RoutedEventHandler(tb_Loaded);
        }
    }

    private void tb_Loaded(object sender, RoutedEventArgs e)
    {
        AddBinding(sender as TextBlock, TextBlock.TextProperty);
    }

    private void AddBinding(DependencyObject targetObj, DependencyProperty targetProp)
    {
        if (IsBinding)
        {
            Binding binding = new Binding();
            binding.Path = new PropertyPath(this.PropertyPath, null);

            BindingOperations.SetBinding(targetObj, targetProp, binding);
        }
        else
        {
            targetObj.SetValue(targetProp, this.PropertyPath);
        }
    }
}

下面是 XAML 中的实现:
<TextBlock >
                <i:Interaction.Behaviors>
                    <behaviors:CustomBindingBehavior PropertyPath="{Binding Path=HeaderPropertyBinding}" IsBinding="{Binding Path=HeaderIsBinding}" />
                </i:Interaction.Behaviors>
            </TextBlock>

问候
强尼

关于wpf - 绑定(bind)一个绑定(bind)的路径属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13524588/

相关文章:

silverlight - 程序员如何与使用 Silverlight 的网页设计师一起工作?

wpf - Silverlight 是否适合大型 LOB 应用程序

android - 无法将 Gradle 项目与数据绑定(bind)库同步

c# - WPF 绑定(bind)问题 - UI 更新,对象不更新

c# - WPF 如何更改页面中的属性?

wpf - 动画结束后关闭 WPF 窗口

c# - 触发其他控制事件时触发控制事件

silverlight - 是否还有其他人在Silverlight中遇到怪异的调试+崩溃行为?

java - 如何在 JavaFX 中将 StringProperty 绑定(bind)到 ObjectProperty<Integer>?

c# - 第一个敏捷项目——我应该先写什么?