Mega Code Archive

 
Categories / VB.Net / WPF
 

Set a Style Programmatically

<Window x:Class="WpfApplication1.Window1"     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"     Loaded="Window_Loaded" Title="WPF" Height="230" Width="140">     <Window.Resources>         <Style x:Key="labelStyle1">             <Setter Property="Label.Background" Value="LightYellow" />             <Setter Property="Label.HorizontalContentAlignment" Value="Center" />         </Style>         <Style x:Key="imageStyle1">             <Setter Property="Image.Source" Value="c:\image.png" />             <Setter Property="Image.Height" Value="140" />             <Setter Property="Image.Width" Value="96" />         </Style>         <Style x:Key="labelStyle2">             <Setter Property="Label.Background" Value="AliceBlue" />             <Setter Property="Label.Foreground" Value="DarkBlue" />         </Style>         <Style x:Key="imageStyle2">             <Setter Property="Image.Source" Value="c:\image.png" />             <Setter Property="Image.Height" Value="140" />             <Setter Property="Image.Width" Value="96" />         </Style>     </Window.Resources>     <StackPanel>         <Image x:Name="img"/>         <Label x:Name="lbl" Content="Hello" />     </StackPanel> </Window> //File:Window.xaml.vb Imports System Imports System.Windows Namespace WpfApplication1   Public Partial Class Window1     Inherits Window     Public Sub New()       InitializeComponent()     End Sub     Private Sub Window_Loaded(sender As Object, e As RoutedEventArgs)       lbl.Style = DirectCast(FindResource("labelStyle2"), Style)       img.Style = DirectCast(FindResource("imageStyle2"), Style)       'lbl.Style = (Style)FindResource("labelStyle1");       'img.Style = (Style)FindResource("imageStyle1");     End Sub   End Class End Namespace