微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

wpf – 绑定绑定的Path属性

是否可以将绑定的Path属性绑定到另一个属性

我想实现这段代码

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

所以我可以动态调整我的实际绑定所引用的属性.

谢谢你的帮助
强尼

解决方法

正如其他海报所提到的,你只能在依赖属性上设置绑定 – 哪条路径不是.根本原因是xaml是被编译的源代码.在编译时,编译器不知道’CurrentPath’的值是什么,并且无法编译.基本上你要做的是运行时反映属性值 – 可以使用你绑定的viewmodel中的另一个属性或使用转换器来完成.

视图模型:

public string CurrentValue
{
    get
    {
         var property = this.GetType().GetProperty(CurrentPath);
         return property.GetValue(this,null);
    }
}

使用转换器:

public class CurrentPathTovalueConverter : IValueConverter
{
    public object Convert(object value,Type targettype,object parameter,CultureInfo culture)
    {
        var viewmodel = (viewmodel)value;
        var property = viewmodel.GetType().GetProperty(viewmodel.CurrentPath);
        var currentValue = property.GetValue(viewmodel,null);
        return currentValue;
    }
    public object ConvertBack(object value,CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

当然,如果你想获得对象的简单属性,这些只能工作 – 如果你想得到更复杂的东西,你的反射代码会变得更加复杂.

除非您正在构建类似属性网格的东西,或者出于某种其他原因,您实际上想要反思应用程序中运行的对象,我建议您重新审视您的设计,因为反射实际上仅适用于少数情况.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐