我有一個 C# WPF 專案,使用 aDataGrid來顯示DataTable. 通過讀取 CSV 檔案(標題數量未知)并使用 CSVHelper nuget 包填充它來填充 DataTable。
using (FileStream? stream = fileInfo.OpenRead())
{
using (StreamReader? reader = new(stream))
using (CsvReader? csv = new(reader, csvConfiguration))
{
using CsvDataReader? dr = new(csv);
dataTable.Load(dr);
}
}
我正在使用以下 XAML 設定顯示此 DataTable。
<DataGrid x:Name="DataGrid"
ItemsSource="{Binding Data, UpdateSourceTrigger=PropertyChanged}"
HorizontalScrollBarVisibility="Visible"
VerticalScrollBarVisibility="Visible"
AlternatingRowBackground="AliceBlue"
AlternationCount="2"
CanUserSortColumns="False"
AutoGeneratingColumn="Data_AutoGeneratingColumn"
IsReadOnly="True"
CanUserReorderColumns="False"
Loaded="Data_Loaded"
>
<DataGrid.ColumnHeaderStyle>
<Style BasedOn="{StaticResource {x:Type DataGridColumnHeader}}" TargetType="DataGridColumnHeader">
<EventSetter Event="Click" Handler="DataGridColumnHeader_Click"/>
</Style>
</DataGrid.ColumnHeaderStyle>
</DataGrid>
我已經為Loaded Event 添加了代碼,用于DataGrid回圈遍歷所有DataGridColumn條目,DataGrid.Columns并將HeaderStyle根據它們是否存在于 aList<string>中來設定它們:
- 選定的標題樣式
- UnSelectedHeaderStyle
foreach (DataGridColumn column in grid.Columns)
{
string headerText = column.Header.ToString();
if (cSVConfigureContext.SelectedColumns.Contains(headerText))
{
column.HeaderStyle = selectedHeaderStyle;
}
else
{
column.HeaderStyle = notSelectedHeaderStyle;
}
}
我還在處理TargetType的ClickDataGridColumnHeader事件,它將HeaderStyle在 1 和 2 之間切換。
private void DataGridColumnHeader_Click(object sender, RoutedEventArgs e)
{
var columnHeader = sender as DataGridColumnHeader;
if (columnHeader != null)
{
string headerText = columnHeader.Content.ToString();
if (cSVConfigureContext.SelectedColumns.Contains(headerText))
{
columnHeader.Style = notSelectedHeaderStyle;
cSVConfigureContext.SelectedColumns.Remove(headerText);
}
else
{
columnHeader.Style = selectedHeaderStyle;
cSVConfigureContext.SelectedColumns.Add(headerText);
}
}
e.Handled = true;
}

This part all seems to work. However, adding a "Reset Headers" button to return to a default set of selected columns, is where things are not working.
If I load the window with the DataGrid and press the Reset button (which runs the same code used in the Loaded event, it works fine. But if I first click on any header to switch its state, the style on the column header does not change. I see the change in the SelectedColumns list of strings but no visual update in the DataGrid until I close that window and re-open a new DataGrid. But I can still click headers to change their state.
I've spent a couple hours googling options for forcing a redraw of the column headers but so far no luck.
任何想法為什么重置按鈕在Click事件后不起作用?
uj5u.com熱心網友回復:
任何想法為什么重置按鈕在 Click 事件后不起作用?
的顯然覆寫或優先于Style的。DataGridColumnHeaderHeaderStyleDataGrid
在設定屬性之前將Style所有DataGridColumnHeader元素的屬性設定為可能會解決您的問題。nullHeaderStyleDataGrid
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/410241.html
標籤:
上一篇:從WPF應用程式(C#)發布請求以下載網路服務器的檔案
下一篇:Azure應用注冊中的用戶分配
