【问题标题】:WPF DataGrid ItemsSource binding is not showing data when binding data in XAML code在 XAML 代码中绑定数据时,WPF DataGrid ItemsSource 绑定不显示数据
【发布时间】:2018-10-01 12:27:56
【问题描述】:

DataGrid 在 XAML 视图代码中绑定时未显示任何值,即使在 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>

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

 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 ;

但这不是必需的。它应该在 Xmal 中作为正常绑定工作

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
        }

【问题讨论】:

  • 我没有发现任何明显的问题。您是否检查过 DataGridCollection 在第一次调用之前是否填充了数据,或者是否曾经使用过 DataGridCollection 的设置器? (使用 f9 设置断点)
  • 我在渲染视图之前尝试了它包含超过 60 个项目
  • 你能显示整个视图模型以及 SaleInvoiceDetialDataGridViewModel 类代码吗?顺便提一句。命名也可以改进,可能是问题的一部分。 Detial 应该是 Detail(a 和 i 切换)。 WPF 通常不会在出现拼写错误的情况下抛出错误。
  • 您如何从后面的代码访问 SaleInvoiceDetialViewModel 实例?请注意,在 ItemsSource Binding 上设置 Mode=TwoWay(以及除 Path 之外的所有其他 Binding 属性)是没有意义的。
  • 问题中添加了SaleInvoiceDetialDataGridViewModel

标签: c# wpf


【解决方案1】:

由于您尚未初始化集合,因此您在网格中看不到任何内容。 由于您正在尝试绑定 DataGrid 的 ItemsSource 属性,因此您需要将数据提供给集合以实际查看任何差异。 然后我假设你知道,当使用 ObservableCollection 时,你可以很容易地维护集合的更新,更多信息在这张票下描述:What is the use of ObservableCollection in .net?

回到你的问题,试试下面的代码:

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

编辑: 初始化后它在我身边的样子:

【讨论】:

    【解决方案2】:

    感谢每一位朋友的贡献。默认情况下,它对我有用,初始化数据网格的属性

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-17
      • 1970-01-01
      • 1970-01-01
      • 2015-11-23
      • 2011-07-10
      • 2011-07-21
      • 1970-01-01
      相关资源
      最近更新 更多