我有一個DataGrid
有一個Jobs
用戶可以添加/更新/刪除的選擇。我的DataGrid
的問題在於,當數據加載到DataGrid
中時,我希望它自動填入一些TextBoxes
,詳細說明DataGrid
中的第一項。我通過在DataGrid
上編寫SelectionChanged
事件的方法來完成此操作;SelectedItem not Loading on DataGrid加載
private void DataGridSelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selectedJob = dataGrid.SelectedItem as JobModel;
//MessageBox.Show(selectedJob.ITName);
if (selectedJob != null)
{
notesTextBox.Text = selectedJob.CaseNotes;
createdPicker.SelectedDate = DateTime.Parse(selectedJob.DateCreated.ToString("yyyy-MM-dd"));
deadlinePicker.SelectedDate = DateTime.Parse(selectedJob.DateDeadline.ToString("yyyy-MM-dd"));
nameTextBox.Text = selectedJob.CaseClient;
itNameComboBox.SelectedItem = selectedJob.ITName;
}
}
這裏的問題是,TextBoxes
(和DatePickers
)未填寫的DataGrid
負載時。但是,如果我取消對MessageBox
的註釋,則會正確填寫數據。這是一個很大的問題,因爲如果DataGrid
中只有一個作業,那麼用戶不能選擇它來刪除或更新它。這裏是DataGrid
本身的XAML
;
<DataGrid x:Name="dataGrid" ColumnWidth="*" IsReadOnly="true"
Margin="10" Grid.ColumnSpan="3" FontSize="18.667"
HeadersVisibility="Column" AutoGenerateColumns="False"
CanUserAddRows="False"
IsSynchronizedWithCurrentItem="True"
EnableRowVirtualization="True"
ItemsSource="{Binding JobsCollectionView}"
MinColumnWidth="0" SelectionChanged="DataGridSelectionChanged">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="{Binding Overdue}" Value="1">
<Setter Property="Background" Value="Red"/>
<Setter Property="FontWeight" Value="Bold"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
<DataGrid.Columns>
<!--<DataGridTextColumn Header="Case NO" Width="*" Binding="{Binding CaseNumber}"/>!-->
<DataGridTextColumn Header="IT Person" Width="*" Binding="{Binding ITName}"/>
<DataGridTextColumn Header="Case Notes" Width="*" Binding="{Binding CaseNotes}"/>
<DataGridTextColumn Header="Date Created" Width="*" Binding="{Binding DateCreated, StringFormat=dd/MM/yyyy}"/>
<DataGridTextColumn Header="Deadline Date" Width="*" Binding="{Binding DateDeadline, StringFormat=dd/MM/yyyy}"/>
<DataGridTextColumn Header="Employee Name" Width="*" Binding="{Binding CaseClient}"/>
</DataGrid.Columns>
</DataGrid>
並填寫DataGrid
的方法;
public void FillDataGrid()
{
_jobDataService = new JobDataService();
var _jobs = new ObservableCollection<JobModel>();
_jobs = _jobDataService.GetJobList();
JobsCollectionView = CollectionViewSource.GetDefaultView(_jobs);
DataContext = this;
foreach (JobModel currentJob in JobsCollectionView)
{
if (DateTime.Now == currentJob.DateDeadline)
{
currentJob.Overdue = 0;
}
else if (DateTime.Now > currentJob.DateDeadline)
{
currentJob.Overdue = 1;
}
}
}
有什麼明顯的,我缺少的是防止被稱爲SelectionChanged
事件?我覺得很奇怪,如果我取消註釋MessageBox
,它的工作方式就像我打算的那樣。
嘗試在方法DataGridSelectionChanged的最後一行放置'MessageBox.Show(selectedJob.ITName);'。 – user1672994
@ user1672994如果它在最後一行,那麼它不會將數據加載到'TextBoxes'中。這裏的要點是,我不想爲了讓數據綁定到「TextBoxes」而不得不顯示消息框。 – CBreeze