I am writing a Windows 8 Store App (Metro / Modern?) and I am creating a control to re-use the formatting on multiple forms. I have created some WPF apps in the past and I attempted to create a Dependency Property the same way that I did in WPF. When I put the control on a form to use it though, I can’t get any value returned.
My personControl.cs WPF class:
public partial class PersonControl : UserControl
{
public PersonControl()
{
InitializeComponent();
}
public static readonly DependencyProperty PersonProperty =
DependencyProperty.Register("thisPerson", typeof(Person), typeof(PersonControl));
public Person thisPerson
{
get
{
return (Person)GetValue(PersonProperty);
}
set
{
SetValue(PersonProperty, value);
}
}
}
for the windows 8 app it requires PropertyMetadata to be added — I’m assuming that this is where I am going wrong, but I haven’t been able to track down what to do instead:
public partial class PersonControl : UserControl
{
public PersonControl()
{
InitializeComponent();
}
public static readonly DependencyProperty PersonProperty =
DependencyProperty.Register("thisPerson", typeof(Person), typeof(PersonControl), new PropertyMetadata(new Person()));
public Person thisPerson
{
get
{
return (Person)GetValue(PersonProperty);
}
set
{
SetValue(PersonProperty, value);
}
}
}
nothing has changed in the usage or binding of the control in the XAML that I know of. I am still using sample data so I create a List(Person) and then make a listbox and bind the listbox to the List(Person).
here is the binding code:
On the usercontrol xaml:
<Grid x:Name=”PersonGrid”>
…….
<TextBox x:Name="txtFirstName" Text="{Binding Path=thisPerson.FirstName, ElementName=This}"></TextBox>
On the mainpage Xaml:
<StackPanel x:Name="layoutRoot">
<ListBox x:Name="myListbox">
<ListBox.ItemTemplate>
<DataTemplate>
<local:PersonControl x:Name="myControl" thisPerson="{Binding Path=.}" Margin="5"></local:PersonControl>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Main page code behind:
List<Person> People = new List<Person>();
… populate data …
myListbox.ItemsSource = People;
As an additional note — when I take the contents of the UserControlXaml and put the UI elements directly into the XAML on the main page, it works fine — it is when I use the UserControl that it fails.
It appears that the line in XAML on the usercontrol:
doesn’t work the same in Windows 8 — when I took out the reference to the ElementName and the DependencyProperty (and just let .Net figure that out on it’s own I guess?) it worked fine.
so:
works fine and the Binding is functional now.