这就是您在 WPF 中执行此操作的方式(使用 DevExpress):
<Window x:Class="MiscSamples.DateRangeGridSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:dxe="http://schemas.devexpress.com/winfx/2008/xaml/editors"
xmlns:dxg="http://schemas.devexpress.com/winfx/2008/xaml/grid"
Title="DateRangeGridSample" Height="300" Width="300">
<DockPanel>
<StackPanel DockPanel.Dock="Top">
<Label Content="Start Date:"/>
<dxe:DateEdit EditValue="{Binding FocusedRow.StartDate, ElementName=Table}"/>
<Label Content="End Date:"/>
<dxe:DateEdit EditValue="{Binding FocusedRow.EndDate, ElementName=Table}"/>
<Button Content="New" Click="NewRow" Margin="10"/>
</StackPanel>
<dxg:GridControl ItemsSource="{Binding}">
<dxg:GridControl.View>
<dxg:TableView x:Name="Table" ShowGroupPanel="False"/>
</dxg:GridControl.View>
<dxg:GridControl.Columns>
<dxg:GridColumn FieldName="StartDate"/>
<dxg:GridColumn FieldName="EndDate"/>
</dxg:GridControl.Columns>
</dxg:GridControl>
</DockPanel>
</Window>
代码背后:
public partial class DateRangeGridSample : Window
{
public ObservableCollection<DateRange> Data { get; set; }
public DateRangeGridSample()
{
InitializeComponent();
DataContext = Data = new ObservableCollection<DateRange>();
}
private void NewRow(object sender, RoutedEventArgs e)
{
Data.Add(new DateRange() {StartDate = DateTime.Today, EndDate = DateTime.Today.AddYears(1)});
}
}
数据项:
public class DateRange: INotifyPropertyChanged
{
private DateTime _startDate;
private DateTime _endDate;
public DateTime StartDate
{
get { return _startDate; }
set
{
_startDate = value;
OnPropertyChanged("StartDate");
}
}
public DateTime EndDate
{
get { return _endDate; }
set
{
_endDate = value;
OnPropertyChanged("EndDate");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
结果:
- 您(通常)不处理 WPF 中的任何事件(按钮单击除外,它也可以替换为命令
- 一切都是通过DataBinding完成的。如果您使用的是 WPF,您确实需要了解这一点。
- WPF 摇滚。只需将我的代码复制并粘贴到 a 中
File -> New Project -> WPF Application
,然后自己查看结果。