Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with applying style on WPF UserControl

I have a user-control and I want to use it in some other project. There is no problem when I set some value to its properties directly:

<local:MyUserControl prop1="val1" prop2="val2">
    ...
</local:MyUserControl>

But I can't apply a style to it. I tried:

<Window ...>
    <Window.Resources>
        <Style x:Key="MyUserControlStyle" TargetType="{x:Type local:MyUserControl}">
            <Setter Property="prop1" Value="val1"/>
            <Setter Property="prop2" Value="val2"/>
        </Style>
    </Window.Resources>

    <Grid>
        <local:MyUserControl Style="{StaticResource ResourceKey=MyUserControlStyle}">
            ...
        </local:MyUserControl>
    </Grid>
</Window>

Where did I wrong? -Thanks

like image 644
Mehdi Avatar asked Sep 19 '11 12:09

Mehdi


1 Answers

Using dear @Mario Vernari's instructions, I found it out that the problem was due to a bad strategy which I'd used to create my UserControl. I wanted to create a UserControl that be able to hold some other ones. So I had tried this:

<UserControl x:Class="MyNamespace.MyUserControl"
             ...
             Style="{DynamicResource ResourceKey=MyUserControlStyle}">
    <UserControl.Resources>
        ...
        <Style x:Key="MyUserControlStyle" TargetType="{x:Type UserControl}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type UserControl}">
                        <Border BorderBrush="{Binding Path=DP1}">
                            ...
                            <ContentPresenter ... Content="{TemplateBinding Content}"/>
                            ...
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </UserControl.Resources>
</UserControl>

Where DP1 is a dependency property of type Brush. The UserControl which has been created through this way works if you set its properties (like DP1) directly. Absolutely this is not the true way as @Mario told me:

...When you use an UserControl, it means that you already know its layout, and there is no need to style the control further. You are defining its style twice at the same time thus results a collision...

And he added:

Instead, you should use a CustomControl; Define the default style in the Themes folder (if you own regular Visual Studio, it makes automatically). Afterward, you may override the default style in your own app. In the same way you would do for a normal base class and its derived.

Follow this: http://www.codeproject.com/KB/WPF/WPFCustomControl.aspx ...

Obviously, in this case we need to derive our lookless control from ContentControl class (instead of Control class). You may take a look at this & this to master the details.

Here, I give thanks to @Mario again. ;)

like image 120
Mehdi Avatar answered Sep 29 '22 07:09

Mehdi