【问题标题】:WPF Update List binded on DataGrid from other Thread & Class从其他线程和类绑定到 DataGrid 的 WPF 更新列表
【发布时间】:2015-11-13 14:27:26
【问题描述】:

回答:

  Application.Current.Dispatcher.Invoke((Action)(() => { logs.Add(this); }));

我尝试为我的服务器创建日志系统 (Log.cs)

我做了这个课程日志:

public class Log
{
    public enum Flags
    {
        [Description("SERVER - OK")]
        OK,
        [Description("SERVER - ERROR")]
        ERROR
    }


    public string EtatLog { get; set; }
    public string MessageLog { get; set; }

    public static ObservableCollection<Log> logs = new ObservableCollection<Log>();

    public Log(Flags flag, string message)
    {
        EtatLog = GetEnumDescription(flag);
        MessageLog = message;

        logs.Add(this);
    }

    private string GetEnumDescription(Enum enumValue)
    {
        var fieldInfo = enumValue.GetType().GetField(enumValue.ToString());

        var descriptionAttributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);

        return descriptionAttributes.Length > 0 ? descriptionAttributes[0].Description : enumValue.ToString();
    }
}

我已经像这样将我的 ObservableCollection 绑定到我的 Datagrid 上:

<DataGrid x:Name="GridLogs" Margin="0,5,0,0" ItemsSource="{Binding}" AutoGenerateColumns="False" x:FieldModifier="public">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding EtatLog}" Header="ID du Logs"/>
        <DataGridTextColumn Binding="{Binding MessageLog}" Header="Message du Logs" Width="*"/>
    </DataGrid.Columns>
</DataGrid>

现在这是我的问题:我想创建一个服务器,所以我使用很多线程来运行它(比如我的登录监听器)。如果我有一个新连接(用户),我想在我的列表中写一个日志,所以我这样做: Log log = new Log(Log.Flags.OK, "New co...");

但是,我使用多线程,所以我的数据网格无法更新,因为它在主线程上运行...

我有这个错误(法语):

我该如何解决我的问题?

【问题讨论】:

    标签: c# wpf multithreading binding datagrid


    【解决方案1】:

    您需要允许主 UI 线程添加到集合中。

    为此使用 Dispatcher

    public Log(Flags flag, string message)
    {
        EtatLog = GetEnumDescription(flag);
        MessageLog = message;
        this.Dispatcher.Invoke((Action)(() => {
            logs.Add(this);
        }
    }
    

    【讨论】:

    • 我不能使用“this”,因为它是“log.cs”类,而不是我的 Mainwindows:/ 我的错误:Dispatcher dosent 存在...
    • 你能用“Application.Current.Dispatcher.Invoke()”吗?
    • 天哪,它起作用了:)谢谢老兄! Application.Current.Dispatcher.Invoke((Action)(() => { logs.Add(this); }));
    猜你喜欢
    • 2014-06-26
    • 2021-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    相关资源
    最近更新 更多