gpt4 book ai didi

wpf - WPF:这种类型的CollectionView不支持更改错误

转载 作者:行者123 更新时间:2023-12-03 03:27:54 24 4
gpt4 key购买 nike

所以我有WPF应用程序,我想添加Logger form

所以我创建了另一个form:

public partial class LoggerForm : MetroWindow
{
public LoggerForm()
{
InitializeComponent();
DataContext = LogHelper.LogEntries;
lvLogger.ItemsSource = LogHelper.LogEntries;
}

public void AddRandomEntry(LogEntry logEntry)
{
Dispatcher.BeginInvoke((Action)(() => LogHelper.LogEntries.Add(logEntry)));
}
}

XAML ListView:
<ListView Name="lvLogger"
Background="#181818"
Margin="0,0,0,0">
<ListView.View>
<GridView>
<GridViewColumn Width="Auto" Header="Time" DisplayMemberBinding="{Binding DateTime}"/>
<GridViewColumn Width="Auto" Header="Index" DisplayMemberBinding="{Binding Index}"/>
<GridViewColumn Width="Auto" Header="Level" DisplayMemberBinding="{Binding Level}"/>
<GridViewColumn Width="Auto" Header="Source" DisplayMemberBinding="{Binding Source}"/>
<GridViewColumn Width="Auto" Header="Message" DisplayMemberBinding="{Binding Message}"/>
</GridView>
</ListView.View>
</ListView>

日志 object:
public class LogEntry
{
public string DateTime { get; set; }

public int Index { get; set; }

public string Source{ get; set; }

public Level Level { get; set; }

public string Message { get; set; }
}

列表:
public class LogHelper
{
public static ObservableCollection<LogEntry> LogEntries { get; set; }
}

因此,这就是我将日志添加到列表中的方式:

打开我的记录仪 form:
Thread newWindowThread = new Thread(new ThreadStart(() =>
{
// Create and show the Window
loggerForm = new LoggerForm();
loggerForm.Show();

// Start the Dispatcher Processing
Dispatcher.Run();
}));

// Set the apartment state.
newWindowThread.SetApartmentState(ApartmentState.STA);
newWindowThread.IsBackground = true;
newWindowThread.Start();

然后从我的主要 form创建 LogEntry对象,然后将其添加:
private void AddLog(Level level, string message)
{
if (loggerForm != null)
{
LogEntry logEntry = new LogEntry()
{
DateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss,fff"),
Index = LogHelper.LogEntries.Count,
Level = level,
Source = "bla bla",
Message = message
};

loggerForm.AddRandomEntry(logEntry);
}
}

因此,在我关闭 Logger表单并再次将其打开之前,它可以正常工作。在这一点上,如果我添加另一个 LogEntry,我在 error方法中有这个 AddRandomEntry:

System.NotSupportedException: 'This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread.'

最佳答案

您的问题是由于您使用了单独的线程。我的建议是根本不要启动您的新线程。

Thread newWindowThread = new Thread(new ThreadStart(() =>


newWindowThread.SetApartmentState(ApartmentState.STA);
newWindowThread.IsBackground = true;
newWindowThread.Start();

都不好
不要这样
为UI拥有多个线程几乎从来不是一个好主意。

关于wpf - WPF:这种类型的CollectionView不支持更改错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49479066/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com