我有一个功能,需要很长时间。
当函数运行时,我想显示一些图片,但这段代码不起作用。为什么?
(我必须只使用框架4 )
这是代码XAML
<Image Width="33" Stretch="Uniform" Source="{Binding ImagePath, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Grid.Column="0"/>
这是代码
public bool Cmd_TestExe()
{
Thread trd_A = new Thread(MyThreadTask_ShowImg);
Thread_Status = false;
trd_A.Start();
if (My_Slow_Function(sCon) == false) {
displayMessage(Status_Failure);}
}
public void Wait(int sleep)
{
dynamic dFrame = new DispatcherFrame();
ThreadPool.QueueUserWorkItem(state =>
{
Thread.Sleep(sleep);
dFrame.Continue = false;
});
Dispatcher.PushFrame(dFrame);
}
public void MyThreadTask_ShowImg()
{
while (Thread_Status == false) {
Application.Current.Dispatcher.Invoke(new Action(() =>
{
if (Second(Now) % (2) == 0) {
ImagePath = "/Images/exit.png";
Wait(250);
} else {
ImagePath = "/Images/excel.png";
Wait(250);
Console.WriteLine(Now);
}
}));
}
}
......这是属性
private string _ImagePath { get; set; }
public string ImagePath {
get { return _ImagePath; }
set {
_ImagePath = value;
OnPropertyChanged("ImagePath");
}
}
答案 0 :(得分:1)
首先,你必须在你的Cmd_TestExe方法中返回一个bool。
其次,我从不使用DispatcherFrame,但这就是我要做的:
public partial class MainWindow : Window
{
Thread myLittleThread;
bool stop;
public string ImageSource
{
set
{
myLittleImage.Source = new BitmapImage(new Uri(value));
}
}
public MainWindow()
{
InitializeComponent();
InitThread();
}
private void InitThread()
{
myLittleThread = new Thread(DoWork);
stop = false;
Application.Current.Exit += MyLittleApplication_Exit;
myLittleThread.Start();
}
private void MyLittleApplication_Exit(object sender,EventArgs e)
{
stop = true;
}
private void DoWork(){
string newImageSource;
while (!stop)
{
if (DateTime.Now.Second % 2 == 0)
{
newImageSource = "SomeRandomFooImage.png";
}
else
{
newImageSource = "MyLittleRandomImage.png";
}
Application.Current.Dispatcher.Invoke(new Action(() =>
{
ImageSource = newImageSource;
}));
Thread.Sleep(250);
}
}
}
和XAML:
<Image Name="myLittleImage" ></Image>