当我尝试执行My Lines of Code
时//使用Staements
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using TwitchLib;
using TwitchLib.Events.Client;
using TwitchLib.Models.Client;
//我的代码行
void PostMessage(string UserName,string UserType, bool isSub, string Message)
{
StackPanel SP = new StackPanel();
SP.Orientation = Orientation.Horizontal;
TextBlock DT = new TextBlock();
DT.Text = DateTime.Now.ToShortTimeString();
SP.Children.Add(DT);
TextBlock Caster = new TextBlock();
TextBlock Type = new TextBlock();
switch (UserType)
{
case "Broadcaster":
Caster.Text = " CASTER ";
SP.Children.Add(Caster);
Type.Text = " MOD ";
SP.Children.Add(Type);
break;
case "Moderator":
Type.Text = " MOD ";
SP.Children.Add(Type);
break;
case "GlobalModerator":
Type.Text = " GMOD ";
SP.Children.Add(Type);
break;
case "Staff":
Type.Text = " STAFF ";
SP.Children.Add(Type);
break;
case "Admin":
Type.Text = " ADMIN ";
SP.Children.Add(Type);
break;
default:
break;
}
if (isSub == true)
{
TextBlock Sub = new TextBlock();
Sub.Text = " SUB ";
SP.Children.Add(Sub);
}
TextBlock UName = new TextBlock();
SP.Children.Add(UName);
UName.Text = " " + UserName + ": ";
TextBlock Mess = new TextBlock() ;
Mess.Text = Message;
SP.Children.Add(Mess);
//ChatWindow.Text += DT + pretag + UserName + Message + Environment.NewLine;
ChatWindow.Dispatcher.Invoke(new Action(() => ChatWindow.Items.Add(SP)));
}
我拉这个异常“调用线程必须是STA,因为许多UI组件都需要这个。”
如果我试试这个
void PostMessage(string UserName,string UserType, bool isSub, string Message)
{
Thread thread = new Thread(() => {
//Same inside Code
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
我拉出异常'调用线程无法访问此对象,因为另一个线程拥有它。'
基本上它把对待就好像调用从未发生过一样 有些人可以给我一些建议。我是使用WPF的新手。