0
希望網格背景每半秒由提供的r,g,b值進行更改,並且仍然能夠與網格內的按鈕進行交互。 問題是背景在regualr時間間隔上都沒有變化,也不允許用戶與網格中的兩個按鈕進行交互。只有當我切換到任何其他應用程序或任務管理器時,網格的顏色纔會更改。如何達到目標?WPF:每半秒更換網格背景並仍然與其他控件交互
<Grid Name="MainGrid" Height="{Binding ElementName=MainWindow1, Path=ActualHeight}" Loaded="MainGrid_Loaded">
<StackPanel VerticalAlignment="Center">
<Label Height="50" Name="xCoordinate" />
<Label Height="50" Name="yCoordinate" />
<StackPanel HorizontalAlignment="Center" Height="50" Orientation="Horizontal">
<Button Content="Red" Width="100" Name="xBtn" Click="xBtn_Click" Margin="0,0,10,0"/>
<Button Content="Blue" Width="100" Name="yBtn" Click="yBtn_Click" />
</StackPanel>
</StackPanel>
</Grid>
public partial class MainWindow : Window
{
Thread thread;
public MainWindow()
{
InitializeComponent();
thread = new Thread(new ThreadStart(ChangeGridColor));
thread.Start();
}
private void xBtn_Click(object sender, RoutedEventArgs e)
{
xCoordinate.Background = new SolidColorBrush(Colors.Red);
}
private void yBtn_Click(object sender, RoutedEventArgs e)
{
yCoordinate.Background = new SolidColorBrush(Colors.Blue);
}
private void MainWindow_MouseMove(object sender, MouseEventArgs e)
{
Point point = Mouse.GetPosition(Application.Current.MainWindow);
xCoordinate.Content = point.X;
yCoordinate.Content = point.Y;
}
byte r=0,g=0,b = 0;
public void ChangeGridColor()
{
while (true)
{
this.Dispatcher.Invoke((Action)(() =>
{//this refer to form in WPF application
MainGrid.Background = new SolidColorBrush(Color.FromRgb(r, g, b));
r += 1;
g += 1;
b += 1;
}));
Thread.Sleep(1000);
}
}
}
爲什麼在代碼中做到這一點?在幾行XAML中使用WPF的故事板 – MickyD