问题
Actual state:
I have a DataGrid with 4 Columns (Icon|DateTime|LogLevel|Message)
I use it as a viewer to present entries of a LogFile.
When opening the Window the UI lags and alot of entries are added one by one to the DataGrid.
Note: I am already using multiple threads. My UI-Thread is not freezing. Its just taking way to long to fill the whole DataGrid.
What I want:
I would prefer something like "pre-render" the whole window before showing it to the user.
When I have aready opened the Window once - every time I open it again, its no problem anymore.(not rendering new .... ?)
What I have tried:
- Setting the VisibilitytoHiddenand wait(Thread.Sleep()) 10 secs then setVisibility = Visibility.Visible;
- Adding all the Data into my DataGridin ViewModel-Constructor
but all this didn't really fix it. I ain't even sure if it's the C# Code or just the Bindings...
This may be a silly question but is there a way to "pre-render" the DataGrid and its Content before displaying it ?
EDIT:
I also use some DataTriggers to set RowColor but this might not be the problem..
Here is some Code I use:
The Entry Class:
 public class LogEntry
{
    public string LogLevel { get; set; }
    public string LogLevelIcon
    {
        get
        {
            switch(LogLevel)
            {
                case "[D]":     //IF DEBUG ENTRY:
                    return "pack://application:,,,/Resources/Bug.png";
                case "[F]":     //IF FATAL ENTRY
                    return "pack://application:,,,/Resources/System-error-alt.png";
                case "[E]":     //IF ERROR ENTRY
                    return "pack://application:,,,/Resources/Error_32_WhiteBackground.png";
                case "[I]":     //IF INFO ENTRY
                    return "pack://application:,,,/Resources/Info_32.png";
                case "[W]":     //IF WARNING ENTRY
                    return "pack://application:,,,/Resources/Warning_32_WhiteBackground.png";
                case "[DB]":    //IF DB ENTRY
                    return "pack://application:,,,/Resources/Database.png";
                default:
                    return string.Empty;
            }                
        }
    }
    public string Message { get; set; }
    public DateTime DateTime { get; set; }
    public override string ToString()
    {
        return $"{LogLevel};{DateTime.ToString("dd.MM.yyyy HH:mm:ss")};{Message}";
    }
}
Getting the Data from my LogFile:
public void ExtractDataFromLogFile(string logFilePath)
    {
        new Thread(() => {
            List<string> linesInFile = new List<string>();
            using (FileStream stream = File.Open(logFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    while (true)
                    {
                        while (!reader.EndOfStream)
                        {
                            ProcessFileContent(reader.ReadLine());
                        }
                        while (reader.EndOfStream)
                        {
                            Thread.Sleep(50);
                        }
                    }
                }
            }
        }).Start();
    }
Adding to the
ObservableCollection<LogEntry>() _logEntries;:
private void ProcessFileContent(string line)
    {
        Match match = _regex.Match(line);
        if (match.Success)
        {
            LogEntry entry = new LogEntry()
            {
                LogLevel = match.Groups[1].ToString(),
                DateTime = DateTime.Parse(match.Groups[2].ToString(), new CultureInfo("de-DE")),
                Message = match.Groups[3].ToString()
            };                    
            _logEntries.Add(entry);                    
        }
    }
Finally the XAML of the DataGrid (Styles left out!):
<DataGrid Grid.Row="1"
          x:Name="DataGrid"
          Grid.ColumnSpan="2"
          Margin="5"
          IsReadOnly="True"
          AutoGenerateColumns="False"
          CanUserReorderColumns="False"
          ItemsSource="{Binding Path=ItemsView, UpdateSourceTrigger=PropertyChanged}">
  <DataGrid.Columns>
            <DataGridTemplateColumn Width="Auto">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Image Source="{Binding Path=LogLevelIcon, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
                               Width="16" 
                               Height="16"></Image>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTextColumn Width="Auto" Header="Datum"
                                Binding="{Binding Path=DateTime, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"/>               
            <DataGridTextColumn Width="*" Header="Meldung"
                                Binding="{Binding Path=Message, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"/>
        </DataGrid.Columns>
    </DataGrid>
Note that "ItemsView" is typeof ICollectionView
I fill it here:
private void InitializeCollection()
    {
        ItemsView = CollectionViewSource.GetDefaultView(_logEntries);
        BindingOperations.EnableCollectionSynchronization(_logEntries, _lock);
    }
回答1:
With reading from file, you should change to:
XAML:
<DataGrid
          Grid.Row="1"
      x:Name="DataGrid"
      Grid.ColumnSpan="2"
      Margin="5"
      IsReadOnly="True"
      AutoGenerateColumns="False"
      CanUserReorderColumns="False" ItemsSource="{Binding}">
    <DataGrid.Columns>
        <DataGridTemplateColumn Width="Auto">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Image Source="{Binding Path=LogLevelIcon, Mode=OneWay}" Width="16" Height="16"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTextColumn Width="Auto" Header="Datum" Binding="{Binding Path=DateTime, Mode=OneWay}"/>
        <DataGridTextColumn Width="*" Header="Meldung" Binding="{Binding Path=Message, Mode=OneWay}"/>
    </DataGrid.Columns>
</DataGrid>
C# code:
Dispatcher DP = Dispatcher.CurrentDispatcher;
public void ExtractDataFromLogFile(string logFilePath)
{
    new Thread(() =>
    {
        var lines = File.ReadAllLines(logFilePath);
        foreach (var line in lines) ProcessFileContent(line);
        DP.Invoke(() => DataGrid.DataContext = _logEntries);
    }).Start();
}
private void ProcessFileContent(string line)
{
    Match match = _regex.Match(line);
    if (match.Success)
    {
        LogEntry entry = new LogEntry()
        {
            LogLevel = match.Groups[1].ToString(),
            DateTime = DateTime.Parse(match.Groups[2].ToString(), new CultureInfo("de-DE")),
            Message = match.Groups[3].ToString()
        };
        _logEntries.Add(entry);
    }
}
If you have any binding to _logEntries, remove it by now.
Call it as below:
ExtractDataFromLogFile("yourLogFile");
This will load your data to _logEntries, after finish, it auto bind to DataGrid.
来源:https://stackoverflow.com/questions/35605199/lifeupdate-datagrid-from-textfile-with-good-performance