我正在编写一个 Windows 8 应用商店应用程序(Metro / Modern?),并且我正在创建一个控件以在多个表单上重新使用格式。我过去创建了一些 WPF 应用程序,并尝试以与在 WPF 中相同的方式创建依赖属性。但是,当我将控件放在表单上以使用它时,我无法返回任何值。
我的 personControl.cs WPF 类:
  公共部分类 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);
        }
    }
}
对于 Windows 8 应用程序,它需要添加 PropertyMetadata ——我假设这是我出错的地方,但我无法追踪要做什么:
公共部分类 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);
        }
    }
}
据我所知,XAML 中控件的使用或绑定没有任何变化。我仍在使用示例数据,因此我创建了一个 List(Person),然后创建了一个列表框并将列表框绑定到 List(Person)。
这是绑定代码:
在用户控件 xaml 上:
<Grid x:Name=”PersonGrid”>
…….
<TextBox x:Name="txtFirstName" Text="{Binding Path=thisPerson.FirstName, ElementName=This}"></TextBox>
在 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>
后面的主页代码:
List<Person> People = new List<Person>();
… populate data … 
myListbox.ItemsSource = People;
作为附加说明——当我获取 UserControlXaml 的内容并将 UI 元素直接放入主页上的 XAML 时,它工作正常——当我使用 UserControl 时它失败了。