默认情况下,它被设置为您可以通过单击标题对DataGrid的列进行排序。 在编程期间,我的程序的行为已经改变,因此我无法对列进行排序。我不知道是什么导致了这个。 XAML:
<Window x:Class="ReportTool.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="{Binding WindowTitle}" Height="306.716" MaxHeight="350" Width="495.149" SizeToContent="WidthAndHeight" ResizeMode="CanMinimize">
<ScrollViewer >
<Grid>
<DataGrid x:Name="DataGridAusgabe" CanUserSortColumns="True" Loaded="DataGridAusgabe_Loaded_1"
AutoGenerateColumns="False" HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
</DataGrid>
</Grid>
</ScrollViewer>
这就是我绑定到DataGrid的方式:
public partial class MainWindow : Window
{
string path = "adressen.txt";
StreamReader sr;
ObservableCollection<String[]> line_list = new ObservableCollection<String[]>();
ObservableCollection<String[]> output_data = new ObservableCollection<string[]>();
public MainWindow()
{
InitializeComponent();
ReadFile(path);
}
void ReadFile(string path)
{
try
{
FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
sr = new StreamReader(fs, Encoding.Default);
while (true)
{
string line = sr.ReadLine();
if (line != "")
{
if (line == null)
{
break;
}
line_list.Add(line.Split(','));
output_data.Add(line.Split(','));
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
this.Close();
}
DataGridAusgabe.AutoGenerateColumns = false;
DataGridAusgabe.Columns.Clear();
var ifaConv = new ItemFromArrayConverter();
int k = 0;
foreach (var header in output_data.First())
{
DataGridAusgabe.Columns.Add(new DataGridTextColumn()
{
Header = header,
Binding = new Binding() { Converter = ifaConv, ConverterParameter = k++ },
});
}
DataGridAusgabe.ItemsSource = output_data.Skip(1);
}
public class ItemFromArrayConverter : IValueConverter
{
#region IValueConverter Member
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var arr = (object[])value;
return arr[int.Parse(parameter.ToString())];
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
#endregion
}
}