问题
I have the following code:
public class MyClass: DynamicObject, INotifyPropertyChanged
{
Dictionary<string, object> properties = new Dictionary<string, object>();
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (properties.ContainsKey(binder.Name))
{
result = properties[binder.Name];
return true;
}
else
{
result = "Invalid Property!";
return false;
}
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
properties[binder.Name] = value;
this.OnPropertyChanged(binder.Name);
return true;
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
dynamic method = properties[binder.Name];
result = method(args[0].ToString(), args[1].ToString());
return true;
}
///.... Rest of the class.
}
When i bind against it from xaml, debug points in TryGetMember is not triggeret. Do i miss something?
<DataTemplate x:Key="SearchResults">
<Grid Width="294" Margin="6">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Border Background="{StaticResource ListViewItemPlaceholderBackgroundThemeBrush}" Margin="0,0,0,10" Width="40" Height="40">
<Image Source="{Binding Path=Banner}" Stretch="UniformToFill"/>
</Border>
<StackPanel Grid.Column="1" Margin="10,-10,0,0">
<TextBlock Text="{Binding SeriesName}" Style="{StaticResource BodyTextStyle}" TextWrapping="NoWrap"/>
<TextBlock Text="{Binding Subtitle}" Style="{StaticResource BodyTextStyle}" Foreground="{StaticResource ApplicationSecondaryForegroundThemeBrush}" TextWrapping="NoWrap"/>
<TextBlock Text="{Binding Overview}" Style="{StaticResource BodyTextStyle}" Foreground="{StaticResource ApplicationSecondaryForegroundThemeBrush}" TextWrapping="NoWrap"/>
</StackPanel>
</Grid>
</DataTemplate>
The datacontext is set to
public ObservableCollection<dynamic> SearchResults {get;set;}
and
ICollection col = item.SearchResults;
this.DefaultViewModel["Results"] = col; //this is the datacontext of the gridview
回答1:
Here is a solution I am using for kind-of dynamic binding. The binding syntax just needs to include []:
public class DynamicLocalSettings : BindableBase
{
public object this[string name]
{
get
{
if (ApplicationData.Current.LocalSettings.Values.ContainsKey(name))
return ApplicationData.Current.LocalSettings.Values[name];
return null;
}
set
{
ApplicationData.Current.LocalSettings.Values[name] = value;
OnPropertyChanged(name);
}
}
}
来源:https://stackoverflow.com/questions/12894952/can-i-bind-against-a-dynamicobject-in-winrt-windows-8-store-apps