在XAML代码中绑定数据时,WPF DataGrid ItemsSource绑定不显示数据

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在XAML代码中绑定数据时,WPF DataGrid ItemsSource绑定不显示数据相关的知识,希望对你有一定的参考价值。

在XAML视图代码中绑定时,DataGrid没有显示任何值,甚至在XAML中定义窗口数据上下文所有其他文本框和同一视图上的组合框数据绑定工作正常所有这些属性都不会粘贴在以下代码中

查看代码

<Window x:Class="MegaSoft.Views.Windows.SaleInvoiceDetialWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MegaSoft.Views.Windows"
        mc:Ignorable="d"
         d:DesignHeight="1500" d:DesignWidth="1200"
        xmlns:uc="clr-namespace:MegaSoft.UserControls"
        xmlns:vm="clr-namespace:MegaSoft.ViewModel"
        WindowState="Maximized"
        Title="Sale Invoice">
      <Window.DataContext>
        <vm:SaleInvoiceDetialViewModel x:Name="_SaleInvoiceDetialViewModel"/>
    </Window.DataContext>
<DataGrid MinHeight="300" MaxHeight="300" MaxWidth="1300" ItemsSource="{Binding Path=DataGridCollection,Mode=TwoWay,NotifyOnTargetUpdated=True,NotifyOnSourceUpdated=True,ValidatesOnDataErrors=True,UpdateSourceTrigger=PropertyChanged,ValidatesOnExceptions=True}" Name="SaleInvoiceDataGrid" RowDetailsVisibilityMode="VisibleWhenSelected" SelectionUnit="CellOrRowHeader" ColumnWidth="Auto" AutoGenerateColumns="False" CanUserAddRows="True" CanUserDeleteRows="True" CanUserReorderColumns="False" >
                        <DataGrid.Columns>
                            <DataGridTextColumn Header="Id" Visibility="Collapsed" Binding="{Binding Path=Id,Mode=OneWay ,ValidatesOnDataErrors=True,UpdateSourceTrigger=PropertyChanged,ValidatesOnExceptions=True}" Width="Auto" CanUserResize="False" ></DataGridTextColumn>
                            <DataGridTextColumn IsReadOnly="True" MaxWidth="100" Header="Sr. No"  Binding="{Binding Path=SRNo,Mode=OneTime ,ValidatesOnDataErrors=True,UpdateSourceTrigger=PropertyChanged,ValidatesOnExceptions=True}" CanUserResize="False"></DataGridTextColumn>


                        </DataGrid.Columns>
                    </DataGrid>
</Window>

View与视图模型绑定,其中包含DataGrid Binding对象的一些和其他对象ViewModel

 public class SaleInvoiceDetialViewModel : INotifyPropertyChanged, IDataErrorInfo
    {
     public ObservableCollection<SaleInvoiceDetialDataGridViewModel> DataGridCollection
        {
            get { return _DataGridCollection; }
            set
            {
                _DataGridCollection = value;
                OnPropertyChanged("DataGridCollection");
            }
        }
 #region PropertyChange
        //public event PropertyChangedEventHandler PropertyChanged;
        public event PropertyChangedEventHandler PropertyChanged;
        /// <summary>
        /// Implemantation of Property change interface
        /// </summary>
        /// <param name="property">Name of property</param>
        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion
// other properties 

}

Datagrid显示我尝试的时候

_FrmSaleInvoiceDetialWindow.SaleInvoiceDataGrid.ItemsSource = DataGridCollection ;

但它不是必需的。它应该在Xaml中作为普通绑定工作

ItemsSource="{Binding Path=DataGridCollection}"

SaleInvoiceDetialDataGridViewModel

       public class SaleInvoiceDetialDataGridViewModel : INotifyPropertyChanged     {
            GetGeneralData getData = new GetGeneralData();

            public static int CountSRN { get; set; } = 1;

            private int? _SRNO;
            public int? SRNo
            {
                get
                {
                    if (_SRNO.HasValue)
                    {
                        return ++_SRNO;
                    }
                    return _SRNO = CountSRN++;
                }
                set
                {
                    _SRNO = value;
                }
            }


            private int _Id;
            public int Id
            {
                get { return _Id; }
                set
                {
                    _Id = value;
                    OnPropertyChanged("Id");
                }
            }

            private int? _ItemAccountId;
            public int? ItemAccountId
            {
                get { return _ItemAccountId; }
                set
                {
                    _ItemAccountId = value;
                    OnPropertyChanged("ItemAccountId");
                    OnPropertyChanged("ProductName");
                    OnPropertyChanged("IsCatchWeight");
                    OnPropertyChanged("CWSize");
                    OnPropertyChanged("CWQty");
                    OnPropertyChanged("Unit");
                }
            }


            private string _ProductName;

            public string ProductName
            {
                get
                {
                    if (ItemAccountId.HasValue)
                        return _ProductName = ItemAccountList.Where(x => x.Id == _ItemAccountId).FirstOrDefault()?.ItemName;
                    return _ProductName;
                }
                set
                {
                    _ProductName = value;
                    OnPropertyChanged("ProductName");
                }
            }

            private bool? _IsCatchWeight;

            public bool? IsCatchWeight
            {
                get
                {
                    if (_ItemAccountId.HasValue)
                        return _IsCatchWeight = Convert.ToBoolean(_ItemAccountList.FirstOrDefault(x => x.Id == ItemAccountId)?.IsCatchWeightItem);
                    return _IsCatchWeight;
                }
                set
                {
                    _IsCatchWeight = value;
                    OnPropertyChanged("IsCatchWeight");
                }
            }



            private double? _CWSize;

            public double? CWSize
            {
                get
                {
                    //if (IsCatchWeight == true)
                    return _CWSize = _ItemAccountList?.FirstOrDefault(x => x.Id == ItemAccountId)?.CWSizeOrConversion;
                    //return _CWSize;
                }
                set
                {
                    _CWSize = value;
                    OnPropertyChanged("CWSize");
                    OnPropertyChanged("Quantity");
                    OnPropertyChanged("ActualPriceAfterDiscount");
                    OnPropertyChanged("NetAmount");
                }
            }

            private double? _CWQty;

            public double? CWQty
            {
                get
                {
                    if (IsCatchWeight != true)
                        return _CWQty = null;
                    return _CWQty;
                }
                set
                {
                    _CWQty = value;
                    OnPropertyChanged("CWQty");
                    OnPropertyChanged("Quantity");
                    OnPropertyChanged("ActualPriceAfterDiscount");
                    OnPropertyChanged("NetAmount");
                }
            }

            private double? _Quantity;

            public double? Quantity
            {
                get
                {
                    if (_IsCatchWeight == true)
                    {
                        if (MaxQuantity.HasValue && _MaxQuantity < (CWQty * CWSize))
                        {
                            CWQty = MaxCWQty;
                        }
                        return _Quantity = CWQty * CWSize;
                    }
                    if(MaxQuantity.HasValue && _Quantity > _MaxQuantity)
                    {
                        _Quantity = _MaxQuantity;
                    }
                    return _Quantity;
                }
                set
                {
                    _Quantity = value;
                    OnPropertyChanged("Quantity");
                    OnPropertyChanged("MaxQuantity");
                    OnPropertyChanged("ActualPriceAfterDiscount");
                    OnPropertyChanged("NetAmount");
                }
            }

            private string _Unit;

            public string Unit
            {
                get
                {
                    if (_ItemAccountId.HasValue)
                        return _Unit = _ItemAccountList?.FirstOrDefault(x => x.Id == ItemAccountId)?.UOM?.Name;
                    return _Unit;
                }
                set
                {
                    _Unit = value;
                    OnPropertyChanged("Unit");
                }
            }

            private float? _UnitPrice;

            public float? UnitPrice
            {
                get { return _UnitPrice; }
                set
                {
                    _UnitPrice = value;
                    OnPropertyChanged("UnitPrice");
                    OnPropertyChanged("ActualPriceAfterDiscount");
                    OnPropertyChanged("NetAmount");
                }
            }

            private float? _Discount;

            public float? Discount
            {
                get { return _Discount; }
                set
                {
                    _Discount = value;
                    OnPropertyChanged("Discount");
                    OnPropertyChanged("ActualPriceAfterDiscount");
                    OnPropertyChanged("NetAmount");
                }
            }

            private int? _DiscountPercent;

            public int? DiscountPercent
            {
                get
                {
                    if (_DiscountPercent == 0)
                        return _DiscountPercent = null;
                    return _DiscountPercent;
                }
                set
                {
                    _DiscountPercent = value;
                    OnPropertyChanged("DiscountPercent");
                    OnPropertyChanged("ActualPriceAfterDiscount");
                    OnPropertyChanged("NetAmount");
                }
            }


            private double? _ActualPriceAfterDiscount;

            public double? ActualPriceAfterDiscount
            {
                get
                {
                    return _ActualPriceAfterDiscount = (UnitPrice - (Discount ?? 0.0)) - ((DiscountPercent.HasValue == true) ? ((UnitPrice - (Discount ?? 0.0)) * (DiscountPercent / 100.0)) : 0.0);
                }
                set
                {
                    _ActualPriceAfterDiscount = value;
                    OnPropertyChanged("ActualPriceAfterDiscount");
                    //OnPropertyChanged("NetAmount");
                }
            }


            private double? _NetAmount;

            public double? NetAmount
            {
                get
                {
                    return _NetAmount = ActualPriceAfterDiscount * _Quantity;
                }
                set
                {
                    _NetAmount = value;
                    OnPropertyChanged("NetAmount");
                }
            }

            private int? _SiteId;

            public int? SiteId
            {
                get { return _SiteId; }
                set
                {
                    _SiteId = value;
                    OnPropertyChanged("SiteId");
                    OnPropertyChanged("WarehouseList");
                    OnPropertyChanged("WarehouseId");
                }
            }

            private int? _WarehouseId;

            public int? WarehouseId
            {
                get
                {
                    if (!_SiteId.HasValue)
                        return _WarehouseId = null;
                    return _WarehouseId;
                }
                set
                {
                    _WarehouseId = value;
                    OnPropertyChanged("WarehouseId");
                }
            }

            private double? _MaxQuantity;

            public double? MaxQuantity
            {
                get { return _MaxQuantity; }
                set
                {
                    _MaxQuantity = value;
                    OnPropertyChanged("MaxQuantity");
                }
            }

            private double? _MaxCWQty;

            public double? MaxCWQty
            {
                get { return _MaxCWQty; }
                set
                {
                    _MaxCWQty = value;
                    OnPropertyChanged("MaxCWQty");
                }
            }

            #region DropDownList

_ItemAccountList = new ObservableCollection<ItemAccount>();
            private static ObservableCollection<ItemAccount> _ItemAccountList = GetGeneralData.GetItemAccountListStatic();

            public static ObservableCollection<ItemAccount> ItemAccountList
            {
                get
                {
                    if (_ItemAccountList.Any() == false)
                        return _ItemAccountList = GetGeneralData.GetItemAccountListStatic();
                    return _ItemAccountList;
                }
                set
                {
                    _ItemAccountList = value;
                    //OnPropertyChanged("ItemAccountList");
                }
            }

            private ObservableCollection<MiscList> _SiteList = new ObservableCollection<MiscList>();

            public ObservableCollection<MiscList> SiteList
            {
                get
                {
                    if (_SiteList.Any() == false)
                        return _SiteList = getData.GetSiteList();
                    return _SiteList;
                }
                set
                {
                    _SiteList = value;
                    OnPropertyChanged("SiteList");
                }
            }

            private ObservableCollection<MiscList> _WarehouseList;

            public ObservableCollection<MiscList> WarehouseList
            {
                get
                {
                    return _WarehouseList = getData.GetWarehouseList(SiteId);
                }
                set
                {
                    _WarehouseList = value;
                    OnPropertyChanged("WarehouseList");
                }
            }

            #endregion

            #region PropertyChange
            public event PropertyChangedEventHandler PropertyChanged;

            protected void OnPropertyChanged(string propertyName)
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }

            #endregion
        }
答案

由于您尚未初始化集合,因此无法在网格中看到任何内容。由于您尝试绑定DataGrid的ItemsSource属性,因此需要将数据提供给集合以实际看到任何差异。然后我假设您知道,当使用ObservableCollection时,您将能够非常轻松地维护集合的更新,更多关于此票据的描述:What is the use of ObservableCollection in .net?

回到您的问题,请尝试以下代码:

    public SaleInvoiceDetialViewModel()
    {
        DataGridCollection = new ObservableCollection<SaleInvoiceDetialDataGridViewModel>
        {
            new SaleInvoiceDetialDataGridViewModel(),
            new SaleInvoiceDetialDataGridViewModel()
        };
    }

编辑:初始化后它在我身边的样子:enter image description here

另一答案

感谢每个好友的贡献。它默认情况下初始化Data Grid的属性

   private ObservableCollection<SaleInvoiceDetialDataGridViewModel> _DataGridCollection = new ObservableCollection<SaleInvoiceDetialDataGridViewModel>();

        public ObservableCollection<SaleInvoiceDetialDataGridViewModel> DataGridCollection
        {
            get
            {
                return _DataGridCollection;
            }
            set
            {
                _DataGridCollection = value;
                OnPropertyChanged("DataGridCollection");
            }
        }

以上是关于在XAML代码中绑定数据时,WPF DataGrid ItemsSource绑定不显示数据的主要内容,如果未能解决你的问题,请参考以下文章

WPF如何更改xaml代码里ListBox的数据绑定

WPF ----在UserControl的xaml里绑定依赖属性

WPF 数据网格绑定工具提示在表格内容绑定刷新时闪烁

如何通过XAML,WPF中的数据绑定设置VisualState INITIALIZATION

如何在 WPF/XAML 中绑定背景颜色?

WPF 绑定