c# - WPF 转换器值类型始终为“RuntimeType”
问题描述
我正在尝试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 语句为 false。
我也试过做typeof(value)
和value.GetType() == typeof(CmQuote)
如何将类型传递给此转换器,并在运行时检查它是否为特定类型?
编辑:添加这样的对象:
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
在转换器中收到的是类型,而不是任何类型的实例。所以GetType()
返回RuntimeType
。
进行强制转换并将 Type 与由typeof()
运算符获得的另一个 Type 进行比较:
public class TypeToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Type t = value as Type;
if (t == typeof(CmQuote))
return Visibility.Visible;
return Visibility.Hidden;
}
}
推荐阅读
- elasticsearch-aggregation - 为什么在大多数情况下深度优先优于广度优先?
- r - Shiny:如何合并和缩写输入以从 Excel 表中提取数据?
- c - realloc 如何管理指针大小?
- google-chrome - 运行 audiocapture 代码时 Chrome 无法检测到捕获设备
- c - C定义第一次不使用时扩展不一样的宏
- c - 通过引用错误传递结构(不完整的结构和重新声明)
- java - 如何按时间戳属性过滤对象数组(通过 - 命令替代 SQL 滞后于分区的代码)
- elasticsearch - 如何在多索引搜索中通过索引获取聚合聚合?
- python - 使用 tensorflow-distributed 实现 mask-r-cnn
- c# - 当列表视图中的项目很少时,标题列的右下角是什么?