Question

To make sure that a binding in WPF is targeting an existing property, I'm using static property-name-properties.

Now I wan't to encapsulate more info about my properties into a static property description object, Name, Type, Id etc, but without having to have one path-bindable property for the name and one property with all other info.

The problem is that WPF complains about the property having the wrong type, not String but PropertyInfo.

I'm trying to get around this limitation somehow. For instance I have tried making my PropertyInfo implicitly castable to string, overriding ToString and adding both a TypeConverter from PropertyInfo to string and to string from PropertyInfo. Nothing works.

And I can't bind directly to the Name-property either.

<TextBlock Text="{Binding Path={x:Static l:Test.TitleProperty}}" />

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        TypeDescriptor.AddAttributes(typeof(string),
          new TypeConverterAttribute(typeof(StringFromPropertyConverter)));

        DataContext = new Test { Title = "hello" };
    }
}

public class Test
{
    public static readonly PropertyInfo TitleProperty = 
      new PropertyInfo { Name = "Title" };

    public string Title { get; set; }
}

[TypeConverter(typeof(PropertyToStringConverter))]
public class PropertyInfo
{
    public string Name { get; set; }

    public static implicit operator string(PropertyInfo p) { return p.Name; }

    public override string ToString()
    {
        return Name;
    }
}

public class PropertyToStringConverter : TypeConverter
{
    public override bool CanConvertTo(ITypeDescriptorContext context,
      Type destinationType)
    {
        if (destinationType == typeof(string)) return true;
        return base.CanConvertTo(context, destinationType);
    }

    public override object ConvertTo(ITypeDescriptorContext context, 
      System.Globalization.CultureInfo culture, object value,
      Type destinationType)
    {
        return ((PropertyInfo)value).Name;
    }
}

public class StringFromPropertyConverter : TypeConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext context,
      Type sourceType)
    {
        if (sourceType == typeof(PropertyInfo)) return true;
        return base.CanConvertFrom(context, sourceType);
    }

    public override object ConvertFrom(ITypeDescriptorContext context, 
      System.Globalization.CultureInfo culture, object value)
    {
        return ((PropertyInfo)value).Name;
    }
}

Any suggestions?

Was it helpful?

Solution

Your PropertyInfo needs to have a TypeConverter to convert PropertyInfo to System.Windows.PropertyPath, not string. Also, you might want to think about reusing .NETs System.Reflection.PropertyInfo for this purpose.

I have seen this approach before and the main reason for it was to avoid "magical strings" in property change notifications. So you might also take a look how to accomplish to get a PropertyInfo using System.Linq.Expressions like this:

public static class ReflectionHelper
{
    public static PropertyInfo GetPropertyInfo<T>(Expression<Func<T, object>> getter)
    {
        return (PropertyInfo)((MemberExpression)getter.Body).Member;
    }
}

And use it like this:

public class Test
{
    public static readonly PropertyInfo TitleProperty = ReflectionHelper.GetPropertyInfo<Test>(x => x.Title);

    public string Title { get; set; }
}

EDIT : NEW ANSWER

Yes, you are right. It doesn't work even if you define TypeConverter to convert PropertyInfo to System.Windows.PropertyPath. I think it is because the ConverterType attribute should be placed on System.Windows.PropertyPath class. But since it is a class that you don't own, you can't place attributes on it. Using the TypeDescriptor to add attribute won't work because XAML doesn't use TypeDescriptor infrastructure.

You can accomplish your conversion with MarkupExtension. Here is a complete code (it uses PropertyInfo from System.Reflection namespace):

ReflectionHelper.cs

using System;
using System.Linq.Expressions;
using System.Reflection;

namespace WpfApplication
{
    public static class ReflectionHelper
    {
        public static PropertyInfo GetPropertyInfo<T>(Expression<Func<T, object>> getter)
        {
            return (PropertyInfo)((MemberExpression)getter.Body).Member;
        }
    }
}

Test.cs

using System.Reflection;

namespace WpfApplication
{
    public class Test
    {
        public static readonly PropertyInfo TitleProperty = ReflectionHelper.GetPropertyInfo<Test>(x => x.Title);

        public string Title { get; set; }
    }
}

PropertyInfoPathExtension.cs

using System;
using System.Reflection;
using System.Windows;
using System.Windows.Markup;

namespace WpfApplication
{
    public class PropertyInfoPathExtension : MarkupExtension
    {
        private readonly PropertyInfo propertyInfo;

        public PropertyInfoPathExtension(PropertyInfo propertyInfo)
        {
            if (propertyInfo == null)
                throw new ArgumentNullException("propertyInfo");

            this.propertyInfo = propertyInfo;
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return new PropertyPath(propertyInfo);
        }
    }
}

MainWindow.xaml

<Window x:Class="WpfApplication.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:Test Title="hello"/>
    </Window.DataContext>
    <TextBlock Text="{Binding Path={local:PropertyInfoPath {x:Static local:Test.TitleProperty}}}"/>
</Window>

OTHER TIPS

So, is your syntax correct?

I had to bind to a static class a while ago. The syntax for binding to a static is different. I documented it here.

WPF Binding to a property of a static class

But essentially the syntax is this:

{x:Static s:MyStaticClass.StaticValue1}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top