我有一个继承自DynamicObject的类,除动态属性外,还有一些静态定义的属性。静态定义的属性在DataTemplate
中绑定没有问题 - 但不是动态属性。
我正在使用Silverlight for WP8 - 不确定这是否与WPF相同。
DynamicObjects是否支持绑定?
编辑:这里摘自代码:
DynamicObject
班ItemContent
:
public class ItemContent : DynamicObject, INotifyPropertyChanged
{
private Dictionary<string, object> propertyBag = new Dictionary<string, object>();
// Statically-defined Property
public string SProperty { get; set; }
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return propertyBag.TryGetValue(binder.Name, out result);
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
if (propertyBag.ContainsKey(binder.Name)){
propertyBag[binder.Name] = value;
} else {
propertyBag.Add(binder.Name, value);
}
RaisePropertyChanged(binder.Name);
return true;
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return propertyBag.Keys;
}
// ... omitted for brevity
}
XAML:
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding SProperty}"/>
<TextBlock Text="{Binding DProperty}"/>
</StackPanel>
</DataTemplate>
摘自ViewModel:
dynamic i1 = new ItemContent() { SProperty = "static property" };
i1.DProperty = "dynamic property";
ObservableCollection<ItemContent> Items = new ObservableCollection<ItemContent>(){ i1 };