这不是一个我坚持的问题,而是一个关于是否有更好的方法的问题。它按原样运作,但如果可以,我希望能更好地理解。
为什么在使用DataGrid.ItemSource
进行绑定时,我始终必须更新ObservableCollection<T>
?
我使用以下代码将ObservableCollection<T>
绑定到DataGrid
。
public partial class MainWindow : INotifyPropertyChanged
{
public MainWindow()
{
DataContext = this;
InitializeComponent();
CalcObservable =
DatabaseQueries.ShiftInputSourceObserv(SelectedEmployee.Key, DateFilter);
MyDataGrid.ItemsSource = CalcObservable;
}
public ObservableCollection<CalcTable> CalcObservable { get; set; }
= new ObservableCollection<CalcTable>();
}
这是从DataBase获取数据的函数,
internal class DatabaseQueries
{
public static ObservableCollection<CalcTable> ShiftInputSourceObserv(int staffNo, DateTime date)
{
using (DatabaseDataContext dataContext = new DatabaseDataContext(MainWindow.InstanceConnectionString))
{
return new ObservableCollection<CalcTable>
(dataContext.CalcTables.Where(
p => p.Staff_No == staffNo &&
p.Year_No == date.Year &&
p.Month_No == date.Month)
.OrderBy(p => p.Column_Index));
}
}
}
然后我使用ComboBox
更改事件来更新ObservableCollection<T>
。 SelectedEmployee.Key
绑定ComboBox
并在选择时更改所选员工:
private void NumbersComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
CalcObservable =
DatabaseQueries.ShiftInputSourceObserv(SelectedEmployee.Key, DateFilter);
MyDataGrid.ItemsSource = CalcObservable;
}
我认为更改ObservableCollection<T>
会更新没有再次使用MyDataGrid.ItemsSource = CalcObservable;
行?
感谢您的帮助。
答案 0 :(得分:3)
我使用以下代码将
<div class="excluded-prices" id="internet"> <div class="ep-checkbox"> <input type="checkbox" id="cbinternet" onchange="check(cbinternet,internet)" class="epc"> </div> <div class="ep-name"> <label class="epn-title">Internet(Cable)</label> <label class="epn-description">Internet is available for the entire property and costs € 14 per day.</label> </div> <div class="ep-price"> <input type="hidden" id="ep_price"> <div class="epp-total"> <p class="total-title">Total</p> <p class="eppt-price">BAM 28</p> </div> </div> </div>
绑定到ObservableCollection<T>
...
不,你不绑定它。您将DataGrid
属性设置为ItemsSource
属性的值。
然后,您在CalcObservable
事件处理程序中将CalcObservable
属性设置为 new ObservableCollection<T>
。这不会以某种方式自动更新NumbersComboBox_SelectionChanged
的{{1}}属性。
如果您实际对<{1}}属性执行 bind ,则可以刷新ItemsSource
,前提是您的类实现了DataGrid
接口并且您引发了CalcObservable
1}} DataGrid
属性的setter中的事件:
INotifyPropertyChanged
另一个选项是清除PropertyChanged
的现有实例并向其添加新项目,而不是每次要更新DataGrid时都创建新的集合。