我正在尝试根据Button
中选择的值来更改ComboBox
的可见性。
[ComboBox
数据源是List<Type>
<ComboBox ItemsSource="{Binding Objects}" SelectedItem="{Binding SelectedObject}"
按钮像这样绑定:
<Button Visibility="{Binding SelectedObject, Converter={StaticResource TypeToVisibilityConverter}, Mode=TwoWay}"/>
TypeToVisibilityConverter:
public class TypeToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null) return null;
if (value is CmQuote)
return Visibility.Visible;
else
return Visibility.Hidden;
}
}
[由于某种原因,当在CmQuote
中选择类型ComboBox
时,value
名称正确,即CmQuote
,但实际类型为RuntimeType
,而不是CmQuote,因此始终使用if语句错误。
我也尝试过typeof(value)
和value.GetType() == typeof(CmQuote)
如何将类型传递给此转换器,并在运行时检查它是否为特定类型?
EDIT:添加这样的对象:
private void InitializeObjects()
{
foreach (var assemblyName in Assembly.GetExecutingAssembly().GetReferencedAssemblies())
{
if (assemblyName.Name == "cmFIX")
{
Assembly assembly = Assembly.Load(assemblyName);
foreach (var type in assembly.GetTypes())
{
if (type.Name.Substring(0, 2) == "Cm")
{
Objects.Add(type);
}
}
}
}
Objects.Add(typeof(string));
}
value
在转换器中收到的是Type,而不是任何类型的实例。因此,GetType()
返回RuntimeType
。
进行转换并比较[Type与另一个由typeof()
运算符获得的Type: