0

I've developed a subclassed ComboBox control in C#, UWP, for enum type properties.

It works great! Almost all the time (... types).

Problem surfaced when the type of the enum was Windows.UI.Text.FontStyle.

The item selection still works right, but what it displays is not the .ToString() values, but Windows.Foundation.IReference`1<Windows.UI.Text.FontStyle> for each item.

When I debug, everything is the same and fine as far as my code is concerned.

My control works by a DependencyProperty called SelectedItemEnum - SelectedItemEnumProperty, which' type is object. And by this binded concrete enum value it sets the ItemsSource:

ItemsSource = Enum.GetValues(SelectedItemEnum.GetType()).Cast<Enum>().ToList();

(And I handle the SelectionChanged event (inside the control) to set the value, but that part always works well.)

George
  • 1
  • 3

1 Answers1

1

I have now been trying this for an hour or so, but I am unable to figure out why this happens and I would definitely be interested to see the real reason behind this.. Apparently there is something about the FontStyle enum, that causes it to get represented as nullable (IReference seems to be "equivalent" to nullable in .NET world).

To solve your problem however, you can build a custom ValueConverter, that will convert the value to string before displaying.

First create a ToStringConverter:

public class ToStringConverter : IValueConverter
{
    public object Convert( object value, Type targetType, object parameter, string language )
    {
        var stringValue = value.ToString();
        return stringValue;
    }

    public object ConvertBack( object value, Type targetType, object parameter, string language )
    {
        throw new NotImplementedException();
    }
}

Now add is as a resource to your page or to the app itself:

<Page.Resources>
    <local:ToStringConverter x:Key="ToStringConverter" />
</Page.Resources>

You can then use it with the combo box as follows:

<local:EnumComboBox x:Name="EnumComboBox">
    <local:EnumComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Converter={StaticResource ToStringConverter}}" />
        </DataTemplate>
    </local:EnumComboBox.ItemTemplate>
</local:EnumComboBox>

This will correctly display the value of the enum. You can see it and try it out in here on my GitHub, along with the sample app I have used to try to figure this out.

I will keep trying to find the reason however, as it does really interest me :-) .

Martin Zikmund
  • 38,440
  • 7
  • 70
  • 91