2

I have a button style in a created style.xaml ResourceDictionary file.

I used this code to call it:

<Button Style="{DynamicResource exitButton}" />

But it didn't recognize the style key either using StaticResource doesn't work too. How to solve this problem?

My style code:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Style x:Key="exitButton" TargetType="Button">
    <Setter Property="Width" Value="22"/>
    <Setter Property="Height" Value="32"/>
    <Setter Property="Background" Value="#FF7070"/>
    <Setter Property="Template">
      <Setter.Value>
        <ControlTemplate TargetType="Button">
          <Border Width="{TemplateBinding Width}"
                  Height="{TemplateBinding Height}"
                  HorizontalAlignment="Center"
                  VerticalAlignment="Center">
            <TextBlock Text="X"
                       FontSize="15"
                       Foreground="White"
                       FontWeight="Bold"/>
          </Border>
        </ControlTemplate>
      </Setter.Value>
    </Setter>
  </Style>
</ResourceDictionary>
1

2 Answers 2

3

You have to import the ResourceDictionary file in your xaml, in the Resources tags.

Something like this:

<UserControl blablabla...>
  <UserControl.Resources>
    <ResourceDictionary>
      <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="/*PROJECT_NAME*;component/*FOLDER_PATH*/style.xaml"/>
      </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
  </USerControl.Resources>

  <!-- the content -->

  ...

  <Button Style="{StaticResource exitButton}"/>

</UserControl>
2

You have two options:

  1. As HasNotifications said, embede the resource into the view that you want the style take affect
  2. Embed the style to the application ResourceDictionary. On that case the style will be available to any view on the application

Add the following code to the App.xaml file:

<Application x:Class="WpfApp1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApp1"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/*PROJECT_NAME*;component/*FOLDER_PATH*/style.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.