WPF中如何为DataGrid选中项添加面试日期列并优化显示
解决方案
1. 修复类型错误并完善addInterviewDT方法
首先你代码里的ShClient是错误类型,应该用ShortlistedClient。另外需要先给TextBox命名并绑定按钮点击事件:
修改XAML元素
给TextBox添加名称,同时给按钮绑定Click事件:
<Button Content="Add Interview DT" Width="128" FontWeight="Bold" Height="28" Click="addInterviewDT"/> <TextBox x:Name="txtInterviewDT" TextWrapping="Wrap" Width="120" Height="46"/>
完善后台方法
// 填充日期时间列的方法 private void addInterviewDT(object sender, RoutedEventArgs e) { var selectedClient = dgr.SelectedItem as ShortlistedClient; // 验证选中项+日期格式合法性 if (selectedClient != null && DateTime.TryParse(txtInterviewDT.Text, out DateTime interviewDT)) { selectedClient.DT = interviewDT; // 如果后续实现了属性通知,这里可以省略刷新 dgr.Items.Refresh(); } }
2. 让“Interview Date and time”列显示为空而非默认值
默认DateTime是值类型,初始值为DateTime.MinValue,改成可空类型就能让未设置的单元格显示为空:
修改ShortlistedClient类
把DT改成可空DateTime?,同时实现INotifyPropertyChanged接口确保UI自动更新:
public class ShortlistedClient : Client, INotifyPropertyChanged { private DateTime? _dt; public DateTime? DT { get => _dt; set { _dt = value; OnPropertyChanged(nameof(DT)); } } public bool InterestedinVac { get; private set; } public List<ShortlistedClient> clients { get; set; } = new List<ShortlistedClient>(); public ShortlistedClient(string n, string p, string e, string l, string wt, string q, string we, string dl, string cc) : base(n, p, e, l, wt, q, we, dl, cc) { DT = null; // 初始化为null,对应空显示 InterestedinVac = false; } // 属性变更通知,用于WPF UI自动更新 public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
修改XAML日期列绑定
设置日期显示格式,同时指定空值显示内容:
<DataGridTextColumn Header="Interview Date and time" Binding="{Binding DT, StringFormat='yyyy/MM/dd HH:mm', TargetNullValue=''}"/>
3. 优化数据源更新(可选)
用ObservableCollection代替List,删除操作后UI会自动更新,无需手动重置数据源:
// 替换List为ObservableCollection ObservableCollection<ShortlistedClient> shlclients = new ObservableCollection<ShortlistedClient>(); public Shortlist() { InitializeComponent(); DataContext = shlclients; shlclients.Add(new ShortlistedClient("Rich", "07515118265", "rich@gmail.com", "Glasgow", "Office", "MSc", "more than 3 years", "Yes", "No")); shlclients.Add(new ShortlistedClient("Steve", "07515118265", "steve@gmail.com", "Glasgow", "Construction", "High School", "more than 3 years", "Yes", "No")); shlclients.Add(new ShortlistedClient("Maria", "07485999005", "mb@gmail.com", "Edinburgh", "Office", "MSc", "more than 3 years", "No", "No")); } // 简化删除方法 private void RemoveShClient(object sender, RoutedEventArgs e) { if (dgr.SelectedItem is ShortlistedClient selectedClient) { shlclients.Remove(selectedClient); } else { // 用WPF自带消息框替代WinForms的 System.Windows.MessageBox.Show("No Clients Found"); } }
内容的提问来源于stack exchange,提问作者Bluetail
相关产品推荐
相关产品推荐

