代码之家  ›  专栏  ›  技术社区  ›  David Ullmer

子属性更改时的DependencyProperty更新

  •  2
  • David Ullmer  · 技术社区  · 7 年前

    在我的UWP应用程序中,我有一个对象,里面有一个列表,如下所示:

    public partial class Test
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public List<string> MyList{ get; set; }
    }
    

    现在我想要一个类型为DependencyProperty的UserControl Test 在我的第1页。它应该用绑定到测试的ItemSoure更新ListView。我的列表。

    如果我添加一个项目进行测试。MyList我希望ListView刷新并显示新项,但我还没有弄清楚如果只有“子属性”发生更改,如何更新DependencyProperty。

    2 回复  |  直到 7 年前
        1
  •  2
  •   Romasz    7 年前

    关联属性 与此无关,因为 ListView。项目资源 使用实现的集合 INotifyCollectionChanged -前面提到了一个很好的例子 ObservableCollection . 此类集合将自动通知UI其更改。

    示例可以如下所示-在用户控件中定义DP:

    public Test MyData
    {
        get { return (Test)GetValue(MyDataProperty); }
        set { SetValue(MyDataProperty, value); }
    }
    
    public static readonly DependencyProperty MyDataProperty =
        DependencyProperty.Register("MyData", typeof(Test), typeof(TestControl), new PropertyMetadata(null));
    

    在xaml中-使用绑定将其设置为的源 列表视图 :

    <ListView Header="{x:Bind MyData.Name}" ItemsSource="{x:Bind MyData.MyList}"/>
    

    一旦你有了这个,只需在你的页面中使用它:

    <local:TestControl Grid.Row="0" Grid.Column="0" MyData="{x:Bind FirstTest}"/>
    <local:TestControl Grid.Row="0" Grid.Column="1" MyData="{x:Bind SecondTest}"/>
    

    当您在后面的一个集合中添加/删除元素时,它应该在UI中更新。几句话-我在这里使用了一次性绑定,就本示例而言,不需要其他方式。您还可以考虑实施 INotifyPropertyChanged公司 在您的 测验 类通知UI其他属性的更改。

    可查看的工作样本 GitHub .

        2
  •  1
  •   nuuse    7 年前

    您应该切换到ObservableCollection,更新属性后,调用 mycollection.Refresh()