Home > Mobile >  WPF Custom-Control Style Not Implemented
WPF Custom-Control Style Not Implemented

Time:10-07

I hope someone can help me please.

I am taking my first tentative steps into WPF by first making a simple custom control. The structure is indicated below.

enter image description here

And the respective code is MainWindow.xaml

<Window x:Class="WPFCustomControl.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WPFCustomControl.NewFolder1"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">

<StackPanel Grid.Row="1">
    <local:MyCustomControl x:Name = "customControl"                                  
     Content = "Click Me" Width = "70" 
     Margin = "10" Click = "customControl_Click"/>
    <TextBlock Name = "txtBlock"  
     Width = "250" Height = "30"/>
</StackPanel>

Generic.xaml

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WPFCustomControl.NewFolder1">

<Style TargetType="{x:Type local:MyCustomControl}" BasedOn = "{StaticResource {x:Type Button}}">
    <Setter Property = "Background" Value = "LightSalmon" />
    <Setter Property = "Foreground" Value = "Blue"/>
</Style>

Everything works as expected. My issue is when I move the Themes folder into the NewFolder1 the application compiles but no Style is implemented.

Thank you in advance for any advice on how to resolve this.

CodePudding user response:

My issue is when I move the Themes folder into the NewFolder1 the application compiles but no Style is implemented.

That's expected. The default style for the control should be located in themes/generic.xaml. This is by convention and where the framework will look for it.

You may move your Style to another ResourceDictionary in NewFolder1 and then modify themes/generic.xaml to merge this one:

<ResourceDictionary
    ..>

    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="pack://application:,,,/WpfCustomControl;component/NewFolder1/YourDictionary.xaml" />
    </ResourceDictionary.MergedDictionaries>

Or you could just define your custom Style directly in themes/generic.xaml.

CodePudding user response:

Most probably you are doing following mistake, go to App.xaml and add Styles as below example

<Application.Resources>
        <!-- Resources scoped at the Application level should be defined here. -->
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="NewFolder1/Generic.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
        
    </Application.Resources>
  • Related