摘要:在下面的例子中:
<Window xmlns=http://schemas.microsoft.com/winfx/avalon/2005
xmlns:x="http://schemas.microsoft.com/winfx/xaml/2005"
>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Button Background="#AA223344" Content ="Button 1" Name="btn1"/>
<Button Background="#AA223344" Grid.Column="1" Content="Button 2" Name="btn2"/>
</Grid>
</Window>
Button1和Button2有着相同的Background,至少在Xaml和在屏幕上看起来如此。但是,Under the hood, 我们看到的是2个不同的SolidColorBrush的实例(instance)。如何能够让2个背景共享一个SolidColorBrush以减少working set(工作集)呢?你可以通过代码,但大多数的情况下我们可以使用Resources.加入:
<Grid.Resources>
<SolidColorBrush x:Key="myBrush1" Color="#AA223344"/>
</Grid.Resources>
然后改写Button的Background,使其通过StaticResource或者DynamicResource引用myBrush1:
<Button Background="{StaticResource myBrush1}" Content ="Button 1" Name="btn1"/>
<Button Background="{StaticResource myBrush1}" Grid.Column="1" Content="Button 2" Name="btn2"/>
在这个简单的示例之中,Button的Background是相对简单的SolidColorBrush。如果使用更复杂的GradientBrush或TileBrush,共享的意义会更大。当然仅从简略Xaml的角度,我们也会在那些情况下使用Resources.
以一道思考题结束:如果不使用Resources,将Button写成
<Button Background="LightYellow" Content ="Button 1" Name="btn1"/>
<Button Background="LightYellow" Grid.Column="1" Content="Button 2" Name="btn2"/>
2个Button会共享同一个SolidColorBrush么?你总是可以通过代码测试的:
if (btn1.Background == btn2.Background)
{
System.Diagnostics.Debug.WriteLine("(1,2) Shared");
}
else
{
System.Diagnostics.Debug.WriteLine("(1,2) Not shared");
}
...[
阅读全文]