这是我的 DataGrid:
<DataGrid x:Name="MoonMining"
ItemsSource="{Binding MarketData.MoonMinerals, ElementName=window}">
<DataGrid.DataContext>
<local:MoonMineral/>
</DataGrid.DataContext>
<DataGrid.Columns>
.. Yes i have columns and they are irrelevant to my question .
</DataGrid.Columns>
</DataGrid>
MarketData 是一个包含我的大部分程序逻辑的类。 MoonMinerals 在该类中定义:
public class MarketData
{
private ObservableCollection<MoonMineral> _moonMinerals = new ObservableCollection<MoonMineral>();
public ObservableCollection<MoonMineral> MoonMinerals
{
get { return _moonMinerals; }
set { _moonMinerals = value; }
}
}
这是我的 MoonMineral 类:
[NotifyPropertyChanged]
public class MoonMineral
{
public MoonMineral()
: this("Def", "Def")
{
}
public MoonMineral(string name, string rarity)
{
Name = name;
Rarity = rarity;
}
public string Name { get; set; }
public double Price { get; set; }
public double Volume { get; set; }
public string Rarity { get; set; }
public double TransportVolume { get; set; }
public double TransportCosts { get; set; }
public double GrossProfit { get; set; }
public double NetProfit { get; set; }
}
如您所见,我正在使用 PostSharp 来清理我的代码,但是当我手动实现 INotifyPropertyChanged 时,我遇到了同样的问题。
现在的问题是我的 DataGrid 不会自行更新,我必须在修改 MoonMinerals 的方法中手动调用它:
var bindingExpression = MoonMining.GetBindingExpression(ItemsControl.ItemsSourceProperty);
if (bindingExpression != null)
bindingExpression.UpdateTarget();
我知道这没什么大不了的,但我想最终设法完全使用 xaml 将数据绑定(bind)到 ui。我以前的所有尝试都涉及在每次更新数据时设置 DataGrids ItemsSource 属性。
请您参考如下方法:
总结一下您正在为 MoonMineral 类实现 INotifyPropertyChanged 接口(interface)的评论,并使用 ObservableCollection 来处理集合的更改,但似乎没有任何地方可以处理对 MoonMinerals 属性的更改
private ObservableCollection<MoonMineral> _moonMinerals = new ObservableCollection<MoonMineral>();
public ObservableCollection<MoonMineral> MoonMinerals
{
get { return _moonMinerals; }
set { _moonMinerals = value; }
}
您可以在公开 MoonMinerals 属性的类中实现 INotifyPropertyChanged 接口(interface),或者将其更改为只读并仅使用 _moonMinerals 的一个实例> 并简单地清除它并添加/删除项目
private readonly ObservableCollection<MoonMineral> _moonMinerals = new ObservableCollection<MoonMineral>();
public ObservableCollection<MoonMineral> MoonMinerals
{
get { return _moonMinerals; }
}
此外,作为旁注,您不需要
<DataGrid.DataContext>
<local:MoonMineral/>
</DataGrid.DataContext>
因为这会将 DataGrid 的 DataContext 设置为 MoonMineral 的新实例。当您使用 ElementName 更改 ItemsSource 的绑定(bind)上下文时,它适用于您的情况,因此在您的情况下不使用 DataContext。
