ComboBox types with ValueConverter and custom attributes

I use MVVM if that matters.

My MainWindowViewModel has two DependencyProperties, TheList and TheSelectedItem . TheList is a List <Type>, TheSelectedItem is a type.

MainWindow has a ComboBox. When MainWindowViewModel loads it, it grabs a list of all the assembly classes that implement IMyInterface, and sets TheList for this .

Each of these classes has a custom attribute called DisplayName, which has one parameter that will be used to display a user-friendly name for the class instead of the name that the application knows for the class.

I also have a ValueConverter for the purpose of converting these types to display names.

    public class TypeToDisplayName : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (targetType.Name == "IEnumerable")
            {
                List<string> returnList = new List<string>();
                if (value is List<Type>)
                {
                    foreach (Type t in value as List<Type>)
                    {
                        returnList.Add(ReflectionHelper.GetDisplayName(t));
                    }
                }

                return returnList;
            }
            else
            {
                throw new NotSupportedException();
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return typeof(BasicTemplate);
        }
    }

So, I end up with a ComboBox with a list of names in it, which the user should be able to understand. Awesome! This is what I want!

Next step: I am binding the SelectedItem property of my ComboBox to TheSelectedItem property in my ViewModel.

Here's the problem: when I make a selection, I get a small red box around my ComboBox, and the TheSelectedItem property on my ViewModel will never be set.

, - ( ComboBox , TheSelectedItem Type - , TheSelectedItem Type, ). , , (, ) DisplayName, ComboBox Type.

. .

+3
2

, ItemsSource ComboBox? , ItemsSource , , , .

<ComboBox ...>
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=typeName, Converter={StaticResource TypeToDisplayNameConverter}}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

.

public class TypeToDisplayNameConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        Type t = (Type)value;
        return ReflectionHelper.GetDisplayName(t);
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return value;
    }
}
+9

, IsSynchronizedWithCurrentItem true ComboBox. ...

+1

Source: https://habr.com/ru/post/1774697/


All Articles