Binding to a BindableCollection inside of a custom object WPF + Caliburn.Micro

时间:2019-03-19 15:02:35

标签: wpf vb.net data-binding caliburn.micro

I have a class Item that has a property of type BindableCollection named Children. Each Child has different information that I need to display, here's an example.

Public Property CurrentItem() As ObservableCollection(Of ItemModel)
        'Used for displaying all item information
        'Will only hold one item
        Get
            Return _currentItem
        End Get
        Set(ByVal value As ObservableCollection(Of ItemModel))
            _currentItem = value
            NotifyOfPropertyChange(Function() CurrentItem)
            NotifyOfPropertyChange(Function() ItemsChildren)
        End Set
End Property

Public Property ItemsChildren() As BindableCollection(Of ChildModel)
            Get
                If CurrentItem.Count > 0 Then
                    Return CurrentItem(0).Children
                Else
                    Return New BindableCollection(Of ChildModel)
                End If
            End Get
            Set(ByVal value As BindableCollection(Of ChildModel))
                _itemChildren = value
            End Set
End Property

XAML

 <!-- Child Info DataGrid-->
    <DataGrid ItemsSource="{Binding Path=ItemsChildren}" Grid.Row="3" Grid.ColumnSpan="2" Margin="10" AutoGenerateColumns="False" AlternatingRowBackground="Gray" CanUserAddRows="False" HorizontalAlignment="Stretch">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Child" Binding="{Binding Path=ChildItem}" />
            <DataGridTextColumn Header="Name" Binding="{Binding Path=ItemName}" />
            <DataGridTextColumn Header="Assy" Binding="{Binding Path=Assembly}"/>
            <DataGridTextColumn Header="Balloon Number" Binding="{Binding Path=BallNo}"/>
            <DataGridTextColumn Header="Link Text" Binding="{Binding Path=LinkText}"/>
            <DataGridTextColumn Header="Qty" Binding="{Binding Path=Quantity}"/>
        </DataGrid.Columns>
    </DataGrid>

ChildModel is just a class that has properties for the values in the datagrid

Both CurrentItem's NotifyOfPropertyChange do not get run when add items to CurrentItem, so ItemsChildren is not being updated. How can I force NotifyOfPropertyChange?

1 个答案:

答案 0 :(得分:0)

不确定是否可以使用,但是在您的代码中CurrentItem是一个ObservableCollection(属于ItemModel)。由于CurrentItem只会保存一个值,因此应该为:

hasattr

当数据网格中的选择更改时,这将触发NotifyOfPropertyChange()。在您的XAML中,您还需要添加SelectedItem属性:

 Public Property CurrentItem() As ItemModel
        'Used for displaying all item information
        'Will only hold one item
        Get
            Return _currentItem
        End Get
        Set(ByVal value As ItemModel
            _currentItem = value
            NotifyOfPropertyChange(Function() CurrentItem)
            NotifyOfPropertyChange(Function() ItemsChildren)
        End Set
End Property

希望这会有所帮助。