Как показать данные из массива в таблице внутри DataGrid? - PullRequest
0 голосов
/ 20 мая 2019

Привет, я работаю с Visual Studio 2019 и WPF, моя цель - это графический интерфейс, в котором пользователь может выбрать машинную переменную, которую пользователь хочет просмотреть.На данный момент у меня есть 2 Datagrid's и 3 Buttons на моем графическом интерфейсе. Я хотел бы прочитать данные из файла и показать данные в левом Datagrid [pic].

Как я могу вставить данные в правую Gridи мой начальник - правильный?размер переменной, мне нужно только имя параметра и адрес внутри моей таблицы.

enter image description here

Я нашел 100 решений для соединения Datagrid с таблицей и SQL-База данных, но не с массивом и таблицей, поэтому, когда кто-то знает лучший подход, пожалуйста, напишите мне.

Для лучшего понимания моего софта Code XAML:

    <Viewbox Margin="0,0,-8,-1">
    <Grid Margin="0,0,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" Width="400" Height="280">
        <DataGrid Name="tableAllVar" ItemsSource ="{Binding}" VerticalAlignment="Top" HorizontalAlignment="Left" Height="220" Width="150" Margin="5,30,0,0" FontSize="6" ColumnHeaderHeight="15" AutoGenerateColumns="True">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Parameter" Binding="{Binding maschinenParameter}" Width="60" />
                <DataGridTextColumn Header="Adresse" Binding="{Binding valueAdresse}" Width="40"/>
            </DataGrid.Columns>
        </DataGrid>
        <DataGrid Name="tableChosenVar" ItemsSource ="{Binding}" VerticalAlignment="Top" HorizontalAlignment="Left" Height="220" Width="150" Margin="240,30,0,0" FontSize="6" ColumnHeaderHeight="15" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Parameter" Binding="{Binding maschinenParameter}" Width="60" />
                <DataGridTextColumn Header="Value" Binding="{Binding maschinenValue}" Width="40"/>
            </DataGrid.Columns>
        </DataGrid>
        <Button Name="buttonAddVar"  HorizontalAlignment="Left" Margin="178,60,0,0" Width="40" Height="40" VerticalAlignment="Top">
            <StackPanel>
                <Image Source="C:\Users\mgleich\source\repos\Inspect\Inspect\Resources\Rechter_Pfeil_48.png"/>
            </StackPanel>
        </Button>
        <Button Name="buttonDeleteVar"  HorizontalAlignment="Left" Margin="178,110,0,0" Width="40" Height="40" VerticalAlignment="Top">
            <StackPanel>
                <Image Source="C:\Users\mgleich\source\repos\Inspect\Inspect\Resources\Löschen_48.png"/>
            </StackPanel>
        </Button>
        <Button Name="buttonSaveVarList"  HorizontalAlignment="Left" Margin="178,160,0,0" Width="40" Height="40" VerticalAlignment="Top">
            <StackPanel>
                <Image Source="C:\Users\mgleich\source\repos\Inspect\Inspect\Resources\schwarz_save_48.png"/>
            </StackPanel>
        </Button>
        <Label Content="Alle Programmvariablen:" HorizontalAlignment="Left" Margin="5,5,0,0" VerticalAlignment="Top" FontSize="8" Height="20" Width="150"/>
        <Label Content="Zu überwachende Variablen:" HorizontalAlignment="Left" Margin="240,5,0,0" VerticalAlignment="Top" FontSize="8" Height="20" Width="150"/>
    </Grid>
</Viewbox>

И моего addVar.CS:

    public partial class addVar : Window
{
    public addVar()
    {
        InitializeComponent();
    }

    private void Window_Activated(object sender, EventArgs e)
    {
        int zahler = 0;

        System.IO.StreamReader sr = new System.IO.StreamReader(@"C:\Users\mgleich\source\repos\Inspect\Variablenliste.txt");   //Erstellung Streamreader
        while (zahler < 2)
        {
            string line = sr.ReadLine();
            if (line != "" && line != null)
            {
                //create a new Row
                string[] linearray = line.Split(' ');
                //add the elements from linearray[0-2] into the new Row 



            }
            else {
                zahler++;
            }

        }
    }//End Window_Activated
}

1 Ответ

1 голос
/ 20 мая 2019

Создайте класс с двумя открытыми string свойствами:

public class YourType
{
    public string maschinenParameter { get; set; }
    public string valueAdresse { get; set; }
}

Затем вы можете создать экземпляр этого класса для каждой строки в файле и добавить их в List<string>, который вы установили.или связать ItemsSource из DataGrid с:

private void Window_Activated(object sender, EventArgs e)
{
    int zahler = 0;

    System.IO.StreamReader sr = new System.IO.StreamReader(@"C:\Users\mgleich\source\repos\Inspect\Variablenliste.txt");   //Erstellung Streamreader
    List<YourType> sourceCollection = new List<YourType>();
    while (zahler < 2)
    {
        string line = sr.ReadLine();
        if (line != "" && line != null)
        {
            //create a new Row
            string[] linearray = line.Split(' ');
            //add the elements from linearray[0-2] into the new Row 
            sourceCollection.Add(new YourType()
            {
                maschinenParameter = linearray[0],
                valueAdresse = linearray[1]
            });
        }
        else
        {
            zahler++;
        }
    }
    tableAllVar.ItemsSource = sourceCollection;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...