【发布时间】:2018-02-22 12:40:36
【问题描述】:
主窗口 XAML:
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="300" Width="500">
<Grid>
<Button Width="300" Height="30" Content="Change All Windows Background Colors To Yellow" Name="Button1" VerticalAlignment="Top" />
<Button Width="300" Height="30" Content="Show Me The Window1" Name="Button2" />
</Grid>
</Window>
Window1 XAML:
<Window x:Class="Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="500">
<Grid>
</Grid>
</Window>
MainWindow vb.net 代码;
Class MainWindow
Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button1.Click
For Each window As Window In Application.Current.Windows
window.Background = New SolidColorBrush(Colors.Yellow)
Next
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button2.Click
Dim myWindow As New Window1()
myWindow.Owner = Application.Current.MainWindow
myWindow.ShowDialog()
End Sub
End Class
重现步骤:
运行这个 WPF 项目。
单击将所有 Windows 背景颜色更改为黄色按钮。
单击 Show Me The Window1 按钮。
问题:为什么Window1的背景颜色没有变成黄色?
【问题讨论】:
-
回答问题的 "why" 部分:因为当您更改背景颜色时该窗口尚不存在(注意 new b> 在
As New Window1())。 -
好的,让我们更容易理解。想象你的窗户是一张纸。它们默认为白色,当有人按下按钮时,您希望它们为黄色。当有人按下“把所有东西都变成黄色”的按钮时,你有两张纸,所以你拿起你的蜡笔,把它们都涂成黄色。然后你会得到一张新的纸——它仍然是白色的,因为你得到了它在你给所有张你有黄色的纸上色。跨度>
-
你自己做怎么样? StackOverflow 不是您所知道的代码编写服务。从长远来看,了解问题并自己解决问题比从互联网上获取完整的解决方案更有价值。提示:JophyJob 走在正确的轨道上,您只需要学习如何使用和应用样式 - 这正是它们在 WPF 中的用途。