平常在用WPF的时候,还是经常用到资源这个东西的,引用资源的时候一般都会用到StaticResource和DynamicResource来引用资源,关于这两个的区别的话我就不多说了,详情可以去参考:用实例讲DynamicResource与StaticResource的区别。我只是想运用DynamicResource来动态的切换样式。从而达到改变一个界面的模板颜色、样式、位置等等。所以来看一个简单的Demo,首先是XAML:
<DockPanel>
<StackPanel DockPanel.Dock="Top">
<Button Name="button" Background="{DynamicResource buttonColor}" Foreground="{DynamicResource foreGround}" Width="100" Height="20" Margin="10" Content="换颜色" Click="Button_Click_1" />
<Popup Name="popup" AllowsTransparency="True" StaysOpen="False" PopupAnimation="Slide"
Placement="Bottom" PlacementTarget="{Binding ElementName=button}">
<Border Margin="0,0,10,10">
<StackPanel>
<Button Click="RectangleBlackButton_Click" Background="Transparent" BorderThickness="0">
<Rectangle Width="100" Height="20" Margin="0,5" Fill="Black" />
</Button>
<Button Click="RectangleGreenButton_Click" Background="Transparent" BorderThickness="0">
<Rectangle Width="100" Height="20" Margin="0,5" Fill="Green" />
</Button>
<Button Click="RectangleBlueButton_Click" Background="Transparent" BorderThickness="0">
<Rectangle Width="100" Height="20" Margin="0,5" Fill="Blue" />
</Button>
</StackPanel>
</Border>
</Popup>
</StackPanel>
</DockPanel>