我正在创建一个小型的wpf程序,它按日期过滤数据集。它最终会对数据进行分组和求和,但目前我只是想显示数据行。我想要一个顶部有ComboBox
的窗口,可以选择日期,DataGrid
显示正确的记录。我已将ComboBox
绑定到可能日期列表,并且我已将标签绑定到ComboBox
更新的值。当我从ComboBox
中选择一个值时,此标签会更新。但是,我无法让DataGrid
更新以显示新数据。
将DataSet
传递给ViewModel构造函数,该构造函数提取两个DataTables
。一个用于为要绑定的ObservableCollection<DateTime>
项创建ComboBox
(通过WorkItemsDates
)。另一个存储为DataGrid
通过过滤(并最终分组/求和等)属性WorkItems
来绑定。 ComboBox
绑定到DateTime
SelectedDate
。标签也绑定到SelectedDate
,以确保ComboBox
Xaml View如下:
<Window ...>
<DockPanel>
<ComboBox DockPanel.Dock="Top"
ItemsSource="{Binding WorkItemsDates}"
SelectedItem="{Binding SelectedDate, Mode=TwoWay}"
ItemStringFormat="ddd d MMM yyyy"
IsSynchronizedWithCurrentItem="True" />
<Label DockPanel.Dock="Bottom"
Content="{Binding SelectedDate, FallbackValue=99/99/9999}"
ContentStringFormat="dd MM yyyy" />
<DataGrid Name="TimeTotalsDataGrid" AutoGenerateColumns="True"
ItemsSource="{Binding WorkItems, Mode=OneWay}"
IsSynchronizedWithCurrentItem="True" ></DataGrid>
</DockPanel>
</Window>
代码背后:
public partial class TheView: Window
{
public UserControl1(DataSet tigerDataSet)
{
InitializeComponent();
DataContext = new TimeTotalsDateSelectorViewModel(tigerDataSet);
}
}
ViewModel如下:
internal class TimeTotalsDateSelectorViewModel
{
private ObservableCollection<DateTime> _workItemsDates;
private DataTable _workItems;
private DateTime _selectedDate;
public TimeTotalsDateSelectorViewModel(DataSet tigerDataSet)
{
if (tigerDataSet == null)
throw new ArgumentNullException("workItemsDates");
if (tigerDataSet.Tables["WorkItemsDates"] == null)
throw new ArgumentNullException("tigerDataSet.Tables[WorkItemsDates]");
if (tigerDataSet.Tables["WorkItems"] == null)
throw new ArgumentNullException("tigerDataSet.Tables[WorkItems]");
_workItems = tigerDataSet.Tables["WorkItems"];
_workItemsDates = new ObservableCollection<DateTime>();
foreach (DataRow row in tigerDataSet.Tables["WorkItemsDates"].Rows)
{
_workItemsDates.Add((DateTime)row["FinishDate"]);
}
SelectedDate = _workItemsDates[0];
}
public ObservableCollection<DateTime> WorkItemsDates
{
get { return _workItemsDates; }
}
public DateTime SelectedDate
{
get { return _selectedDate; }
set { _selectedDate = value; }
}
public DataTable WorkItems
{
get
{
DataRow[] _workItemsToShow = _workItems.Select("FinishTime>='" + _selectedDate.ToString() + "' AND FinishTime<'" + _selectedDate.AddDays(1).ToString() + "'");
return _workItemsToShow.Count() != 0 ? _workItemsToShow.CopyToDataTable() : null;
}
}
答案 0 :(得分:1)
首先,当您使用MVVM
时,您必须通过实施INotifyPropertyChanged
界面来通知您的媒体资源。
从Setter
属性的SelectedItem
开始,您必须同时通知您的WorkItems
媒体资源,这样当您从下拉列表中更改日期时,它也会更新{ {1}}的{1}}。
答案 1 :(得分:0)
在SelectedDate的setter中,调用获取网格值的代码。您也应该实现INotifyPropertyChanged,因此UI将更新数据,用户可以看到它。