Украина |
Стили и ресурсы
Шаг 2. Динамическое применение стилей в коде приложения
Стили также можно создавать и применять динамически в коде приложения. Давайте посмотрим на простой пример создания такого стиля.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace StylesAndResources { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void OnResources(object sender, RoutedEventArgs e) { new ResourceDemo().Show(); } } }
<Window x:Class="StylesAndResources.ResourceDemo" xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml Title="Resource Demo" Height="300" Width="300"> <StackPanel x:Name="myContainer"> <StackPanel.Resources> <LinearGradientBrush x:Key="MyGradientBrush" StartPoint="0,0" EndPoint="0.3,1"> <GradientStop Offset="0.0" Color="LightCyan" /> <GradientStop Offset="0.14" Color="Cyan" /> <GradientStop Offset="0.7" Color="DarkCyan" /> </LinearGradientBrush> </StackPanel.Resources> <Button Width="200" Height="50" Foreground="White" Margin="5" Background="{StaticResource MyGradientBrush}" Content="Click Me!" /> <Button Name="button1" Width="220" Height="50" Margin="5" Click="button1_Click"/> <Button Name="button2" Width="200" Height="50" Foreground="White" Margin="5" Background="{DynamicResource MyGradientBrush}" Content="Change Resource" Click="button2_Click" /> </StackPanel> </Window>
Создадим еще одну страницу и реализуем обработчик первой кнопки так, чтобы при нажатии на нее открывалась новая страница:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace StylesAndResources { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void OnResources(object sender, RoutedEventArgs e) { new ResourceDemo().Show(); } } }
<Window x:Class="StylesAndResources.ResourceDemo" xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml Title="Resource Demo" Height="300" Width="300"> <StackPanel x:Name="myContainer"> <StackPanel.Resources> <LinearGradientBrush x:Key="MyGradientBrush" StartPoint="0,0" EndPoint="0.3,1"> <GradientStop Offset="0.0" Color="LightCyan" /> <GradientStop Offset="0.14" Color="Cyan" /> <GradientStop Offset="0.7" Color="DarkCyan" /> </LinearGradientBrush> </StackPanel.Resources> <Button Width="200" Height="50" Foreground="White" Margin="5" Background="{StaticResource MyGradientBrush}" Content="Click Me!" /> <Button Name="button1" Width="220" Height="50" Margin="5" Click="button1_Click"/> <Button Name="button2" Width="200" Height="50" Foreground="White" Margin="5" Background="{DynamicResource MyGradientBrush}" Content="Change Resource" Click="button2_Click" /> </StackPanel> </Window>
Тут мы задали стиль MyGradientBrush и у нас есть три кнопки. Для первой мы просто используем этот стиль. А для остальных будем менять его динамически.
В обработчике нажатия на первую кнопку нам нужно найти стиль MyGradientBrush и применить его к текущей кнопке.
private void button1_Click(object sender, RoutedEventArgs e) { Control ctrl = sender as Control; ctrl.Background = ctrl.FindResource("MyGradientBrush") as Brush; }
Для второй кнопки мы создадим несколько другой алгоритм. Сначала мы очистим всю коллекцию стилей для данной страницы. После этого мы создадим кисть и добавим ее в коллекцию стилей сстриницы.
private void button2_Click(object sender, RoutedEventArgs e) { myContainer.Resources.Clear(); var brush = new LinearGradientBrush { StartPoint = new Point(0, 0), EndPoint = new Point(0, 1) }; brush.GradientStops = new GradientStopCollection() { new GradientStop(Colors.White, 0.0), new GradientStop(Colors.Yellow, 0.14), new GradientStop(Colors.YellowGreen, 0.7) }; myContainer.Resources.Add("MyGradientBrush", brush); }
Обратите внимание на то, что теперь новый стиль будет применяться и к кнопке button1, в то время как кпопка со статическим стилем не изменится.
Весь код этой страницы выглядит вот так:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace StylesAndResources { /// <summary> /// Interaction logic for ResourceDemo.xaml /// </summary> public partial class ResourceDemo : Window { public ResourceDemo() { InitializeComponent(); } private void button1_Click(object sender, RoutedEventArgs e) { Control ctrl = sender as Control; ctrl.Background = ctrl.FindResource("MyGradientBrush") as Brush; } private void button2_Click(object sender, RoutedEventArgs e) { myContainer.Resources.Clear(); var brush = new LinearGradientBrush { StartPoint = new Point(0, 0, EndPoint = new Point(0, 1) }; brush.GradientStops = new GradientStopCollection() { new GradientStop(Colors.White, 0.0), new GradientStop(Colors.Yellow, 0.14), new GradientStop(Colors.YellowGreen, 0.7) }; myContainer.Resources.Add("MyGradientBrush", brush); } } }
Краткие итоги
Стили – это очень важный инструмент при работе с XAML, Windows Presentation Foundation и Silverlight. В данной лабораторной работе мы рассмотрели несколько возможных способов их использования.