i know there's a lot of these type of questions. i wanted to post so that i can share my specific prob because im getting frustrated.
im running a thread which query path from db and put it in the image element.problem is, i created the image in xaml so when i run this thread it throws the cannot access this object error which it cant access the image element.
then how do i set it without using xaml??here's my code snippet:
public partial class Window1 : Window
{
Thread Frame1;
public Window1()
{
InitializeComponent();
intializeDb();
#region start frame 1 thread
Frame1 = new Thread(frame1);
Frame1.SetApartmentState(ApartmentState.STA);
Frame1.IsBackground = true;
Frame1.Start();
#endregion
}
public void frame1()
{
string k;
command.CommandText = "SELECT * FROM imageframe1";
sqlConn.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
BitmapImage logo = new BitmapImage();
logo.BeginInit();
k = (string)(Reader.GetValue(1));
logo.UriSource = new Uri(k);
logo.EndInit();
image1.Source = logo; //THROWS THE ERROR HERE.IT CANT ACCESS image1
Thread.Sleep(1000);
}
sqlConn.Close();
Reader.Close();
}
how would i access image1
then? if i create a new one within the thread,i will have to put as child of a panel,an then im gonna get an error which it cant access the panel.
any way around this?glad if someone can write an example based on my snippet.
edited with still no success and producing the same error:
public partial class Window1 : Window
{
public readonly SynchronizationContext mySynchronizationContext;
public Window1()
{
InitializeComponent();
mySynchronizationContext = SynchronizationContext.Current;
Frame1 = new Thread(frame1);
Frame1.SetApartmentState(ApartmentState.STA);
Frame1.IsBackground = true;
Frame1.Start();
}
public void frame1()
{
string k;
command.CommandText = "SELECT * FROM imageframe1";
sqlConn.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
BitmapImage logo = new BitmapImage();
logo.BeginInit();
k = (string)(Reader.GetValue(1));
logo.UriSource = new Uri(k);
logo.EndInit();
SendOrPostCallback callback = _ =>
{
image1.Source = logo;
};
mySynchronizationContext.Send(callback, null);
//image1.Source = logo;
Thread.Sleep(1000);
}
sqlConn.Close();
Reader.Close();
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…