2011-05-10 54 views
1

如果我讓視圖模型定義如下:的Silverlight綁定到一個項目在一個字典

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。

+0

你有沒有嘗試讓你的ViewModel [自定義類型描述符](http://msdn.microsoft.com/en-us/library/system.componentmodel.icustomtypedescriptor.aspx)?我不知道Silverlight是否支持這一點。 – Will 2011-05-10 13:14:53

回答

1

嘗試此「{結合屬性[歡迎]}」

+0

我很擔心INotifyCollectionChanged實現將需要這個。解決:http://www.basarat.com/2011/05/observabledictionary-for-silverlight.html因此接受。儘管如此,仍然存在IDataErrorInfo的問題。 – basarat 2011-05-12 04:33:29

1

問題是,當一個基準由類型爲dynamic的標識符認爲DynamicObject僅發揮了作用。

但是Silverlight的XAML中處理工作與objectdynamic並使用反射來確定它需要的酒店信息。

Oliver指出的一個選擇是使用Silverlight與基於string的索引器一起工作的能力。

+0

只是FYI。我正在使用視圖模型定位器。 viewmodel定位器上viewmodel的屬性是動態類型的。該視圖將其綁定到其datacontext。但它仍然不起作用。 PS:我不需要在WPF上做到這一點,以使其發揮作用。它只是。 – basarat 2011-05-10 14:10:01

相關問題