依赖项属性数据绑定返回空值



我正在编写一个Windows 8应用商店应用程序(Metro/Modern?),并且正在创建一个控件以在多个窗体上重用格式。 我过去创建过一些 WPF 应用程序,并尝试以与在 WPF 中相同的方式创建依赖项属性。 但是,当我将控件放在窗体上以使用它时,我无法返回任何值。

我的人控件.cs WPF 类:
公共分部类 人员控件:用户控件 {

    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 应用程序,它需要添加属性元数据 - 我假设这是我出错的地方,但我无法追踪该怎么做:

公共分部类 人员控件:用户控件 {

    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 中控件的使用或绑定没有任何变化。 我仍在使用示例数据,所以我创建了一个列表(人员),然后创建一个列表框并将列表框绑定到列表(人员)。


下面是绑定代码:

在用户控件 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时,它失败了。

IIRC,仅当值与默认值不同时,SetProperty 调用才会注册更改。 同样,IIRC,SetProperty不会比较实际对象,只是是否设置了对对象的引用(对象。等于与对象 != 空)。 通过使用此代码...

new PropertyMetadata(new Person()));

SetValue 无法按预期工作,因为它有一个对象,并且分配一个新对象不会导致属性更新。 更改为

new PropertyMetadata(null)

我认为事情会正常进行。

有点匆忙,所以也许我错过了一些东西...

似乎用户控件上的 XAML 中的行:

<TextBox x:Name="txtFirstName" Text="{Binding Path=thisPerson.FirstName, ElementName=This}">

在Windows 8中的工作方式不同 - 当我取出对ElementName和DependencyProperty的引用时(我猜只是让.Net自己弄清楚?)它工作正常。

所以:

 <TextBox x:Name="txtFirstName" Text="{Binding Path=FirstName}"></TextBox>

工作正常,绑定现在可以正常工作。

最新更新