我遇到了系結到 ObservableCollection 的 XAML DataGrid 的問題。我有3個班級,A,B,C。這個想法是通過使用 Linq 查詢 A 和 B 來生成 C 的 ObservableCollection。
課程
public class A
{
public int Id { get; set; }
public string Name { get; set; }
}
public class B
{
public int Id { get; set; }
public int Age { get; set; }
}
public class C
{
public string Name { get; set; }
public int Age { get; set; }
}
資料背景關系類
private ObservableCollection<A> _as;
public ObservableCollection<A> As
{
get => _as;
set { SetProperty(ref _as, value); }
}
private ObservableCollection<B> _bs;
public ObservableCollection<B> Bs
{
get => _bs;
set { SetProperty(ref _as, value); }
}
public ObservableCollection<C> Cs
{
get
{
var query = from x in As
join y in Bs
on x.Id equals y.Id
select new C() { Name = x.Name, Age = y.Age };
return new ObservableCollection<C>(query);
}
}
MyView.xaml
<DataGrid ItemsSource="{Binding Cs}" Grid.Row="1"/>
如果我通過洗掉一個專案來更新 ObservableCollection "As",我可以通過斷點看到 ObservableCollection "Cs" 也被更新以反映更改,但 UI 上的 Datagrid 保持不變。任何指標的幫助都會很棒,謝謝
uj5u.com熱心網友回復:
您必須RaiseNotifyPropertyChangedwhenAs或Bschange 觸發系結更新Cs:
private ObservableCollection<A> _as;
public ObservableCollection<A> As
{
get => _as;
set
{
if (SetProperty(ref _as, value))
RaisePropertyChanged(nameof(Cs));
}
}
private ObservableCollection<B> _bs;
public ObservableCollection<B> Bs
{
get => _bs;
set
{
if (SetProperty(ref _as, value))
RaisePropertyChanged(nameof(Cs));
}
}
public IEnumerable<C> Cs
{
get
{
var query = from x in As
join y in Bs
on x.Id equals y.Id
select new C() { Name = x.Name, Age = y.Age };
return query;
}
}
此外,您希望' 或' 的內容在不替換整個集合的情況下發生變化,RaisePropertyChanged即AsBs
public ObservableCollection<A> As
{
get => _as;
set
{
if (_as != null)
_as.CollectionChanged -= NotifyCs;
if (SetProperty(ref _as, value))
RaisePropertyChanged(nameof(Cs));
if (_as != null)
_as.CollectionChanged = NotifyCs;
}
}
private void NotifyCs( object sender, CollectionChangedEventArgs args ) => RaisePropertyChanged(nameof(Cs));
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/496851.html
