XAML标记绑定到类型为Type的键的字典

Mar*_*ter 7 .net wpf xaml markup-extensions

我正试图绑定到一个Dictionary<Type,string>通过xaml.

问题是,索引[]Binding标记扩展解释它作为字符串的内容.那个案子有某种'unescape-sequence'吗?

<TextBox Text="{Binding theDictionary[{x:Type ns:OnePrettyType}]}" />
Run Code Online (Sandbox Code Playgroud)

(绑定不起作用,因为{x:Type ns:OnePrettyType}它是作为字符串发送的)

H.B*_*.B. 12

如果索引器具有特定类型,则应自动完成转换,因此这应该有效:

{Binding theDictionary[ns:OnePrettyType]}
Run Code Online (Sandbox Code Playgroud)

如果您需要明确的解释,您可以尝试这样的"演员":

{Binding theDictionary[(sys:Type)ns:OnePrettyType]}
Run Code Online (Sandbox Code Playgroud)

(当然,sys映射到System命名空间的位置)

那将是理论,但所有这些都行不通.首先,如果使用Binding采用路径的构造函数,则会忽略强制转换,因为它PropertyPath以某种方式使用某个构造函数.您还会收到绑定错误:

System.Windows.Data错误:40:BindingExpression路径错误:'object'''Dictionary`2'上找不到'[]'属性

你需要PropertyPath通过避免Binding构造函数使它构造通过类型转换器:

{Binding Path=theDictionary[(sys:Type)ns:OnePrettyType]}
Run Code Online (Sandbox Code Playgroud)

现在这很可能只是抛出异常:

{"Path indexer参数具有无法解析为指定类型的值:'sys:Type'"}

所以很遗憾没有默认的类型转换.然后你可以PropertyPath在XAML中构造一个并确保传入一个类型,但是这个类并不打算在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());
    }
}
Run Code Online (Sandbox Code Playgroud)

然后可以这样使用:

<Binding>
    <Binding.Path>
        <me:PathConstructor Path="theDictionary[(0)]">
            <x:Type TypeName="ns:OnePrettyType" />
        </me:PathConstructor>
    </Binding.Path>
</Binding>
Run Code Online (Sandbox Code Playgroud)

或者像这样

{Binding Path={me:PathConstructor theDictionary[(0)], {x:Type ns:OnePrettyType}}}
Run Code Online (Sandbox Code Playgroud)