0

我正在编写一个 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”&gt;
…….
<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 时它失败了。

4

2 回答 2

1

IIRC,如果值与默认值不同,则 SetProperty 调用只会导致注册更改。同样,IIRC,SetProperty 不比较实际对象,只要对对象的引用是否已设置(object.Equals vs. object != null)。通过使用此代码...

new PropertyMetadata(new Person()));

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

new PropertyMetadata(null)

我认为事情会正常进行。

有点匆忙,所以也许我错过了什么......

于 2013-01-23T03:27:39.083 回答
0

用户控件上的 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>

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

于 2013-01-24T03:32:11.303 回答