Ant*_*ton 3 wpf binding types ivalueconverter
我正在使用MVVM,以防它有所作为.
我的MainWindowViewModel有两个DependencyProperties,TheList和TheSelectedItem.List是List <Type>,TheSelectedItem是Type.
MainWindow有一个ComboBox.当MainWindowViewModel加载它抓住所有的组件实现类的列表IMyInterface的和设置的thelist了这一点.
这些类中的每一个都有一个名为DisplayName的自定义属性,它有一个参数,用于显示类的用户友好名称,而不是应用程序知道的类名.
我还有一个ValueConverter,其目的是将这些类型转换为显示名称.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
所以,我最后得到的是一个ComboBox,其中包含用户应该能够理解的名称列表.真棒!这正是我想要的!
下一步:我将ComboBox的SelectedItem属性绑定到ViewModel中的TheSelectedItem属性.
这是问题所在:当我做出选择时,我的ComboBox周围会出现一个小红框,我的ViewModel上的TheSelectedItem属性永远不会被设置.
我很确定这是因为类型不匹配(ComboBox中的项目现在看起来是字符串,而且TheSelectedItem的类型是Type -也是,当我将TheSelectedItem更改为字符串而不是Type时,它可以工作).但我不知道我需要从哪里开始编码以将ComboBox中的(希望是唯一的)DisplayName转换回Type对象.
在此先感谢您的帮助.我对这个很难过.
如果我正确理解您的问题,那么您在ComboBox的ItemsSource上使用该转换器?在这种情况下,我认为你可以让ItemsSource像它一样,而只是转换每个类型时,像这样.
<ComboBox ...>
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=typeName, Converter={StaticResource TypeToDisplayNameConverter}}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
Run Code Online (Sandbox Code Playgroud)
然后只需转换转换器中的每种类型.
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;
}
}
Run Code Online (Sandbox Code Playgroud)