我有一個DataGrid。其中一列是一個帶有CheckBox的模板。當Checked或Unchecked事件觸發(它發生在兩者中)時,CheckBox的DataContext有時爲空,這會導致我的代碼出錯。如果鼠標在按下並快速釋放按鈕(它是間歇性的)時移動,它似乎最常出現空白。,CheckBox的DataContext有時在選中/取消選中時爲空
我聽了更改CheckBox的DataContext的通過使訪問量:ListenCheckBox(擴展複選框)和附加綁定,它從來沒有設置到空,但它是從零的時候我不會設定一個任務不會期望,即DataGrid完全生成後,您正在檢查/取消選中框。緊接在[un] checked事件運行一個空的DataContext之後,我得到了顯示DataContext從null更改爲Task的通知,所以看起來當我得到一個空的DataContext時,這是因爲它沒有真正設置DataContext當它運行Checked/Unchecked事件時。
此外,我將Tag =「{Binding}」添加到CheckBox進行調試。標記不是空(即它有適當的對象)比DataContext更頻繁,但仍然不是全部。
這裏是XAML代碼的相關位:
<navigation:Page.Resources>
<sdk:DataGridTemplateColumn x:Key="DeleteOrPrintSelect" Header="Delete Or Print Notes Selection">
<sdk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<views:ListenCheckBox IsChecked="{Binding DeleteOrPrintNotesSelection, Mode=TwoWay}" Checked="DeletePrintNotesCheckBox_Changed" Unchecked="DeletePrintNotesCheckBox_Changed" HorizontalAlignment="Center" VerticalAlignment="Center" Tag="{Binding}" />
</DataTemplate>
</sdk:DataGridTemplateColumn.CellTemplate>
</sdk:DataGridTemplateColumn>
</navigation:Page.Resources>
<sdk:DataGrid x:Name="dataGrid1" Grid.Column="1" Grid.Row="2" AutoGeneratingColumn="dataGrid1_AutoGeneratingColumn">
<sdk:DataGrid.RowGroupHeaderStyles>
[removed]
</sdk:DataGrid.RowGroupHeaderStyles>
</sdk:DataGrid>
和相關的代碼背後:
// Create a collection to store task data.
ObservableCollection<Task> taskList = new ObservableCollection<Task>();
[code adding Tasks to taskList removed]
PagedCollectionView panelListView = new PagedCollectionView(taskList);
this.dataGrid1.ItemsSource = panelListView;
}
private void dataGrid1_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyName == "DeleteOrPrintNotesSelection")
{
e.Column = Resources["DeleteOrPrintSelect"] as DataGridTemplateColumn;
}
else
{
e.Column.IsReadOnly = true;
}
}
private void DeletePrintNotesCheckBox_Changed(object sender, RoutedEventArgs e)
{
try
{
var cb = sender as CheckBox;
var t = cb.DataContext as Task;
t.DeleteOrPrintNotesSelection = cb.IsChecked == true;
PagedCollectionView pcv = this.dataGrid1.ItemsSource as PagedCollectionView;
ObservableCollection<Task> taskList = pcv.SourceCollection as ObservableCollection<Task>;
bool anySelected = taskList.Any(x => x.DeleteOrPrintNotesSelection);
this.btnPrint.IsEnabled = anySelected;
this.btnDelete.IsEnabled = anySelected;
}
catch (Exception ex)
{
ErrorMessageBox.Show("recheck", ex, this);
}
}
任何想法?提前致謝。
@Downvoters照顧解釋? –