Binding the Path Property of a Binding

前端 未结 5 1785
广开言路
广开言路 2020-12-11 09:24

is it possible to bind the Path property of a binding to another property?

I want to realize this code:

Text=\"{Binding Path={Binding Path=CurrentPat         


        
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-11 10:10

    As other posters have mentioned, you can only set a binding on a dependency property - which path is not. The underlying reason is that xaml is source code that gets compiled. At compile time the compiler has no idea what the value of 'CurrentPath' is, and would not be able to compile. Essentially what you are looking to do is runtime reflection of a property value - which could be done using another property in the ViewModel you are binding to, or using a converter.

    ViewModel:

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

    Using a converter:

    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, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    

    Of couse these only work if you want to get a simple property of the object - if you want to get something more complex your reflection code is going to get a lot more complex.

    Unless you are building something like a property grid, or for some other reason you actually want to introspect the objects running in your application, I would suggest you revisit your design, as reflection is really only suited to a few situations.

提交回复
热议问题