【发布时间】:2014-12-02 09:00:48
【问题描述】:
这是与WPF Binding : Casting in binding path 类似的问题,我需要在 XAML 绑定语句中强制转换对象。但我似乎无法理解如何在我的特定情况下制作绑定。
该问题的答案参考PropertyPath XAML Syntax,相关部分是(我相信)Single Property, Attached or Otherwise Type-Qualified。
就我而言,在我的主视图模型中,我有一个字典,将字符串映射到实现基本接口的对象:
Dictionary<string, IFlintStone> FlintStones { get; set;}
public interface IFlintStone { Walk, Talk etc}
public class FlintStone : IFlintStone { .. }
但是,我也有这些附加对象和接口,它们是基础对象的子类:
public interface IFred : IFlintStone { Eat, Drink, Yell etc }
public interface IWilma : IFlintStone { Wash, Clean, Cook etc }
public class Fred : FlintStone, IFred {..}
public class Wilma : FlintStone, IWilma {..}
最终我会像这样填充我的字典:
FlintStones["Fred"] = new Fred();
FlintStones["Wilma"] = new Wilma();
现在,在我的 XAML 中,我有一个用于呈现 Fred 对象的用户控件,还有一个用于呈现 Wilma 对象的用户控件。我可以设置这些用户控件的数据上下文,例如:
<FredControl DataContext="{Binding Path=FlintStones[Fred]}" />
<WilmaControl DataContext="{Binding Path=FlintStones[Wilma]}" />
但是我的理解是,这只会将这些对象的 IFlintStone 组件暴露给它们各自的用户控件。但我想将IFred 暴露给<FredControl> 和IWilma 暴露给<WilmaControl>
这可能吗?在这种情况下,绑定语法是什么?
使用我上面引用的链接中的想法,我尝试了以下方法:
<FredControl DataContext="{Binding path=(myns:Fred.FlintStones[Fred])}" />
和
<FredControl DataContext="{Binding path=(myns:Fred).FlintStones[Fred]}" />
(其中myns 是一个xaml 命名空间定义,指向程序集中的Fred 对象。)
但程序要么在启动时崩溃并烧毁,要么抱怨找不到Fred 作为当前数据上下文的属性。
【问题讨论】: