I came across a question that how can we apply the style defined in XAML on any control. Let’s take a look at the style first. Here is a style we define in XAML.
<Setter Property="Margin" Value="5"/>
<Setter Property="Background" Value="Wheat"/>
<Setter Property="FontSize" Value="18"/>
</Style>
Suppose we define few button control in Stack Panel and we want to change the style of button when user click it. Here is a code to define 4 button in Stack Panel.
<Button>Button 1</Button>
<Button>Button 2</Button>
<Button>Button 3</Button>
<Button>Button 4</Button>
</StackPanel>
Because we are going to call the same method on all the button, therefore it perfectly make sense to use the EventSetter here. We are going to define one more style which set the EventSetter property. Here is a XAML code for our other style. Note that we didn’t specify its name, therefore it is going to apply on all the button controls.
<EventSetter Event="Click" Handler="btnClick"/>
</Style>
If our event handler code, we simply search the resource by style name and set the button Style property to that. Here is a C# code to demonstrate this.
{
if (sender as Button != null)
{
if (FindResource("myButtonStyle") as Style != null)
{
((Button)sender).Style = FindResource("myButtonStyle") as Style;
}
}
}
Here is complete XAML code of the program.
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style TargetType="Button">
<EventSetter Event="Click" Handler="btnClick"/>
</Style>
<Style x:Key="myButtonStyle" TargetType="Button">
<Setter Property="Margin" Value="5"/>
<Setter Property="Background" Value="Wheat"/>
<Setter Property="FontSize" Value="18"/>
</Style>
</Window.Resources>
<StackPanel>
<Button>Button 1</Button>
<Button>Button 2</Button>
<Button>Button 3</Button>
<Button>Button 4</Button>
</StackPanel>
</Window>
And here is complete C# code of the program.
using System.Windows.Controls;
namespace WpfStyle
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
void btnClick(object sender, RoutedEventArgs e)
{
if (sender as Button != null)
{
if (FindResource("myButtonStyle") as Style != null)
{
((Button)sender).Style = FindResource("myButtonStyle") as Style;
}
}
}
}
}
Here is the output of the program, when user click third and fourth button.
Leave a comment