I have a UserControl which is used as the basis for items in an ItemsControl:
Main Page xaml:
<ItemsControl ItemsSource="{Binding Systems, Mode=TwoWay}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:ServerGroupControl>
<local:ServerGroupControl.DataContext>
<local:ServerGroupControlViewModel System="{Binding}"/>
</local:ServerGroupControl.DataContext>
</local:ServerGroupControl>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
I am trying to set the ‘System’ property of each ViewModel (such that it can handle the data for the view), but the property is never set!
Here is the dependancy property declaration in the view model class:
public static readonly DependencyProperty SystemProperty = DependencyProperty.Register(
"System",
typeof(ServerGroup),
typeof(ServerGroupControlViewModel)
);
public ServerGroup System
{
get { return (ServerGroup)GetValue(SystemProperty); }
set { SetValue(SystemProperty, value); }
}
The property always keeps it’s default value. Any ideas on why this setup does not work?
So based on your comment i would suspect that the binding does not work because there is no
DataContextin the place where you try to bind.Your VM is not a
FrameworkElementso it has noDataContextproperty, presumably it is notFreezableeither (and hence might lack an inheritance context too) so i suspect that this won’t work. (ElementNameandRelativeSourcewon’t work either then, by the way)I suggest you approach this differently, also i do not recommend the use of DPs in VMs due to thread-affinity and other problems.
Here’s one gem of a work-around:
Yeah, please don’t do that…