【问题标题】:DependencyProperty Update on child property changes子属性更改的 DependencyProperty 更新
【发布时间】:2018-01-04 13:32:23
【问题描述】:

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

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

现在我希望在我的 Page1 中有一个 DependencyProperty 类型为 Test 的 UserControl。它应该使用绑定到 Test.MyList 的 ItemSoure 更新 ListView。

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

【问题讨论】:

    标签: c# uwp dependency-properties


    【解决方案1】:

    DependencyProperty 与这里无关,因为 ListView.ItemsSource 使用实现了 INotifyCollectionChanged 的集合 - 这里的一个很好的例子在 @ 之前提到过987654321@。此类集合将自动通知 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 的源:

    <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 中更新。几句话 - 我在这里使用了 OneTime 绑定,就本示例而言,它不需要其他方式。您也可以考虑在您的 Test 类中实现 INotifyPropertyChanged 以通知 UI 其他属性的更改。

    您可以在GitHub查看工作示例。

    【讨论】:

    • ObservableCollection 仅在添加/删除项目时通知 UI,尽管文档可能会给出不同的氛围。如果您想对集合的每个项目进行任何类型的修改,您实际上必须在集合的每个项目上实现 INotifyPropertyChanged。
    • @AndréB 没错,我只提到了 OP 的问题,他想在哪里看到添加的新项目。 INotifyPropertyChanged 将需要所有可以更改并应反映在 UI 中的内容。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2016-07-21
      • 2013-11-02
      • 2019-07-08
      • 1970-01-01
      • 1970-01-01
      • 2013-11-02
      • 1970-01-01
      • 2021-07-31
      • 2012-04-02
      相关资源
      最近更新 更多