【问题标题】:Silverlight Binding to an item in a DictionarySilverlight 绑定到字典中的项目
【发布时间】:2011-05-10 12:12:04
【问题描述】:

如果我将 ViewModel 定义为以下内容:

public class MainViewModel : DynamicObject
{
    public Dictionary<string, string> Attributes { get; set; }
    public MainViewModel()
    {
        Attributes = new Dictionary<string, string>();
        Attributes["Welcome"] = "Welcome to MVVM Light";
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        if (Attributes.ContainsKey(binder.Name))
        {
            result = Attributes[binder.Name];             
        }
        else
            result = "";
        return true;
    }
}

在silverlight中我收到以下错误:

System.Windows.Data Error: BindingExpression path error: 'Welcome' property not found on 'DictionaryBasedVM.ViewModel.MainViewModel' 'DictionaryBasedVM.ViewModel.MainViewModel' (HashCode=30542218). BindingExpression: Path='Welcome' DataItem='DictionaryBasedVM.ViewModel.MainViewModel' (HashCode=30542218); target element is 'System.Windows.Controls.TextBlock' (Name=''); target property is 'Text' (type 'System.String')..

同样适用于 WPF。

【问题讨论】:

  • 您是否尝试过将您的 ViewModel 设为 custom type descriptor?我不知道 Silverlight 是否支持这个。

标签: wpf silverlight silverlight-4.0 mvvm wpf-4.0


【解决方案1】:

试试这个“{Binding Attributes[Welcome]}”

【讨论】:

【解决方案2】:

问题是DynamicObject 仅在引用被键入为dynamic 的标识符持有时才起作用。

但是,Silverlight Xaml 处理与 object 而不是 dynamic 一起使用,并使用反射来确定它需要的属性信息。

Oliver 指出的一种选择是使用 Silverlight 的能力来处理基于 string 的索引器。

【讨论】:

  • 仅供参考。我正在使用视图模型定位器。视图模型定位器上的视图模型属性是动态类型的。视图将其绑定到其数据上下文。但它仍然不起作用。 PS:我不需要在 WPF 上执行此操作即可使其正常工作。就是这样。
猜你喜欢
  • 2011-02-07
  • 2012-02-29
  • 2011-02-28
  • 1970-01-01
  • 1970-01-01
  • 2014-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多