Silverlight 绑定到字典中的项目
如果我将 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 中同样可以正常工作。
If I make the ViewModel definition to the following :
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;
}
}
In silverlight I get the following error:
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')..
The same works fine in WPF.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个“{绑定属性[欢迎]}”
Try this "{Binding Attributes[Welcome]}"
问题在于,
DynamicObject
仅在引用由类型为dynamic
的标识符保存时才发挥作用。然而,Silverlight Xaml 处理适用于
object
而不是dynamic
,并使用反射来确定它所需的属性信息。Oliver 指出的一种选择是使用 Silverlight 的功能来处理基于字符串的索引器。
The problem is that
DynamicObject
only comes into play when a reference is held by an identifier typed asdynamic
.However Silverlight Xaml processing works with
object
notdynamic
and uses reflection to determine the property info it needs.One option as Oliver points out is to use Silverlight's ability to work with
string
based indexers.