如果索引器具有特定类型,则应自动完成转换,这样应该可以:
{Binding theDictionary[ns:OnePrettyType]}
如果你需要一个明确的解释,你可以尝试这样的“演员”:
{Binding theDictionary[(sys:Type)ns:OnePrettyType]}
(当然sys 映射到System 命名空间)
理论上是这样,但所有这些都行不通。首先,如果您使用采用路径的Binding 构造函数,则转换将被忽略,因为它以某种方式使用PropertyPath 的某个构造函数。你也会得到一个绑定错误:
System.Windows.Data 错误:40:BindingExpression 路径错误:在“object”“Dictionary`2”上找不到“[]”属性
您需要通过类型转换器构造PropertyPath,避免Binding 构造函数:
{Binding Path=theDictionary[(sys:Type)ns:OnePrettyType]}
现在这很可能只是抛出一个异常:
{"路径索引器参数的值无法解析为指定类型:'sys:Type'"}
所以很遗憾没有进行默认类型转换。然后,您可以在 XAML 中构造一个 PropertyPath 并确保传入了一个类型,但该类并不打算在 XAML 中使用,并且如果您尝试会抛出异常,这也很不幸。
一种解决方法是创建一个进行构造的标记扩展,例如
[ContentProperty("Parameters")]
public class PathConstructor : MarkupExtension
{
public string Path { get; set; }
public IList Parameters { get; set; }
public PathConstructor()
{
Parameters = new List<object>();
}
public PathConstructor(string path, object p0)
{
Path = path;
Parameters = new[] { p0 };
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return new PropertyPath(Path, Parameters.Cast<object>().ToArray());
}
}
然后可以这样使用:
<Binding>
<Binding.Path>
<me:PathConstructor Path="theDictionary[(0)]">
<x:Type TypeName="ns:OnePrettyType" />
</me:PathConstructor>
</Binding.Path>
</Binding>
或者像这样
{Binding Path={me:PathConstructor theDictionary[(0)], {x:Type ns:OnePrettyType}}}