更新:2007 年 11 月
此示例演示如何更改 Border 元素的 Background 颜色。
示例
下面的示例将 Button 元素放在 Canvas 的中心附近。Canvas 嵌套在 Border 元素中以显示元素周围的边框。单击 Button 元素时,Border 元素的 Brush 颜色会更改为 LightSteelBlue。单击事件还会将 TextBlock 中的文本字符串添加到 Canvas(表明事件已发生)并更新 Button 元素的文本内容。
<Window
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
x:Class="Border_change_programmatic.Window1"
Title="Change Border Programmatically">
<Border Name="root"
BorderThickness="2"
BorderBrush="Black"
Background="LightGray"
Width="350"
Height="350">
<Canvas>
<Button Name="btn" Canvas.Top="40" Canvas.Left="40" Background="LightSkyBlue" Height="35" Click="ChangeBG">Click Me to change the Background Color</Button>
<TextBlock Canvas.Top="130" Canvas.Left="40" Name="Text1">Waiting for Click!</TextBlock>
</Canvas>
</Border>
</Window>
以下代码隐藏文件将处理 ChangeBG 方法。
Private Sub ChangeBG(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs)
root.Background = System.Windows.Media.Brushes.LightSteelBlue
btn.Content = "Clicked!"
Text1.Text = "The background is now LightSteelBlue"
End Sub
void ChangeBG(object sender, System.Windows.RoutedEventArgs e)
{
root.Background = System.Windows.Media.Brushes.LightSteelBlue;
btn.Content = "Clicked!";
Text1.Text = "The background is now LightSteelBlue";
}