<DataGrid.Columns>
<DataGridTextColumn Header="A" Width="150" Binding="{Binding A}"/>
<DataGridTextColumn Header="B" Width="100" Binding="{Binding B}"/>
<DataGridTextColumn Header="C" Width="100" Binding="{Binding C}"/>
<DataGridTextColumn Header="D" Width="100" Binding="{Binding D}"/>
<DataGridTextColumn Header="E" Width="100" Binding="{Binding E}"/>
<DataGridTextColumn Header="F" Width="100" Binding="{Binding F}"/>
<DataGrid.Columns/>
现在我想从文本文件1,2,3,4,5,6取代A,B,C,D,E,F。我该怎么做?
答案 0 :(得分:0)
要阅读文本文件,您可以使用StreamReader:
using (var reader = new StreamReader(File.OpenRead("c:/yourfile.txt"),
Encoding.GetEncoding("iso-8859-1")))
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(';'); // replace ';' by the your separator
string header1 = values[0];
string header2 = values[1];
string header3 = values[2];
//...
}
}
对于DataGrid标头,您必须将每个标头绑定到属性。您可以尝试这种实现:
*。XAML
<Grid Background="White" x:Name="Layout">
<DataGrid x:Name="grid" ItemsSource="{Binding MyCollection}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding FirstName}">
<DataGridTextColumn.Header>
<TextBlock DataContext="{Binding ElementName=Layout, Path=DataContext}" Text="{Binding Header1}"/>
</DataGridTextColumn.Header>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
代码背后 *的.cs
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainViewModel();
Layout.DataContext = this.DataContext;
}
和ViewModel *的.cs
private string header1;
public string Header1
{
get
{
return header1;
}
set
{
this.header1 = value;
this.NotifyPropertyChanged("Header1");
}
}
修改强> 如果您不使用MVVM,可以尝试这种方法:
* CS
string Header1 = string.Empty;
using (var reader = new StreamReader(File.OpenRead("c:/yourfile.txt"),
Encoding.GetEncoding("iso-8859-1")))
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(';'); // replace ';' by the your separator
Header1 = values[0];
//...
}
}
grid.Columns[0].Header = Header1;
*。XAML
<DataGrid.Columns>
<DataGridTextColumn Width="150" Binding="{Binding A}"/>
<DataGrid.Columns/>