如何从记事本文本文件到datagrid标题获取值?我只想把标题不是数据

时间:2016-04-28 06:29:38

标签: c# wpf sqlite

<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。我该怎么做?

1 个答案:

答案 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/>