首页 > 解决方案 > WPF 绑定到用户控件数据网格

问题描述

我有一个用户控件,我试图在许多实例中使用它。但我似乎无法让绑定正常工作。

我拥有的控制 XAML:

<UserControl x:Class="EveCommon.WPF.Inventory.EveInventoryGrid"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:EveCommon.WPF.Inventory"
         mc:Ignorable="d" 
         x:Name="uc"
         d:DesignHeight="450" d:DesignWidth="800">
<UserControl.Resources>
    <Style x:Key="HeaderRightJustify" TargetType="DataGridColumnHeader">
        <Setter Property="HorizontalContentAlignment" Value="Right"/>
    </Style>
    <Style x:Key="ColumnRight" TargetType="DataGridCell">
        <Setter Property="HorizontalContentAlignment" Value="Right"/>
    </Style>
</UserControl.Resources>
<Grid>
    <DataGrid x:Name="ItemsDG" IsReadOnly="True" ItemsSource="{Binding Path=Inventory, ElementName=uc}" AutoGenerateColumns="False">
        <DataGrid.Columns>
        <!-- SETUP COLUMNS HERE -->
        </DataGrid.Columns>
    </DataGrid>
</Grid>

以及背后的代码:

public partial class EveInventoryGrid : UserControl
{
    public static DependencyProperty InventoryProperty = DependencyProperty.Register(
        "Inventory", 
        typeof(EveInventory),
        typeof(EveInventoryGrid));

    public EveInventory Inventory
    {
        get { return (EveInventory)GetValue(InventoryProperty); }
        set { SetValue(InventoryProperty, value); }
    }
}

最后是来自主窗口的调用。

<inventory:EveInventoryGrid x:Name="ItemsView" Grid.Column="1" Inventory="{Binding Path=Inventory}"  ShowName="True" ShowCost="True"/>

Inventory 是 EveInventory 的一个实例,并且确实实现了 INotifyPropertyChanged。

我只是看不到/不明白我在这里缺少什么。

标签: c#wpf

解决方案


如上所述,您必须在使用 Bindings 时使用ObservableCollection<T>而不是. 否则系统将无法识别更改并且不会更新 UI。List<T>INotifyPropertyChanged


推荐阅读