我创建了一个链接到以下功能的按钮:
private void btnSetVal_Click_1(object sender, RoutedEventArgs e)
{
//VolumeMeter.Value = Convert.ToInt32(txtValue.Text);
int l_iMilSecs = 1000;
VolumeMeter.fSetVal(20);
Thread.Sleep(l_iMilSecs);
VolumeMeter.Value = 30;
Thread.Sleep(l_iMilSecs);
VolumeMeter.Value = 40;
Thread.Sleep(l_iMilSecs);
VolumeMeter.Value = 50;
Thread.Sleep(l_iMilSecs);
VolumeMeter.Value = 60;
}
函数fSetVal - 更新用户控件可见性。 在运行时,btnSetVal_Click_1使线程进入休眠状态(多次调用sleep),但只执行最后一次调用fSetVal .. 我已经尝试将关键字volatile添加到函数中,但它甚至没有编译,所以它可能不是正确的方法.. 有人想过如何预防吗?
fSetVal:
public void fSetVal(int p_iNewVal)
{
//Amit: Set the first X(p_iNewVal ) rectangles visible.
int l_iLastVisibleIndex = m_iNumOfRectangles - p_iNewVal -1;
for (int i = m_iNumOfRectangles - 1; i > l_iLastVisibleIndex; --i)
{
unifGridVolumeMeter.Children[i].Visibility = Visibility.Visible;
}
//Amit: Set the rest of the rectangles to invisible:
for (int i = 0; i <= l_iLastVisibleIndex; i++)
{
unifGridVolumeMeter.Children[i].Visibility = Visibility.Hidden;
}
}
答案 0 :(得分:1)
问题是你在UI线程上睡觉,这意味着UI无法更新。
相反,您应该使用计时器,例如一个DispatcherTimer
重复调用一个方法(直到它完成)。
或者,制作您的方法async
并使用Task.Delay
代替Thread.Sleep
:
private async void btnSetVal_Click_1(object sender, RoutedEventArgs e)
{
// TODO: Use a loop instead of this repeated code...
int l_iMilSecs = 1000;
VolumeMeter.fSetVal(20);
await Task.Delay(l_iMilSecs);
VolumeMeter.Value = 30;
await Task.Delay(l_iMilSecs);
VolumeMeter.Value = 40;
await Task.Delay(l_iMilSecs);
VolumeMeter.Value = 50;
await Task.Delay(l_iMilSecs);
VolumeMeter.Value = 60;
}
另一种方法是利用WPF中广泛的动画支持......