c# - 在 WPF UserControl 上应用样式的问题

标签 c# wpf user-controls coding-style

我有一个用户控件,我想在其他项目中使用它。当我直接为其属性设置一些值时没有问题:

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

但我无法对其应用样式。我试过:

<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>

我哪里做错了? -谢谢

最佳答案

使用亲爱的@Mario Vernari 的说明,我发现问题是由于我用来创建我的 UserControl 的错误策略造成的。我想创建一个能够容纳其他一些用户控件的用户控件。所以我试过这个:

<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>

其中 DP1Brush 类型的依赖属性。如果您直接设置其属性(如 DP1),则通过这种方式创建的 UserControl 可以正常工作。这绝对不是@Mario 告诉我的正确方法:

...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...

他补充说:

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 ...

显然,在这种情况下,我们需要从 ContentControl 类(而不是 Control 类)派生我们的 lookless 控件。你可以看看this & this掌握细节。

在此,再次感谢@Mario。 ;)

关于c# - 在 WPF UserControl 上应用样式的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7470621/

相关文章:

c# - 使用正则表达式提取数据 url

wpf - 为什么我的 WPF 数据网格中有奇怪的退格字符?

c# - 使用两个图像创建按钮样式

html - 如何分别控制Shiny中selectInput的标签和选择文本的字体大小样式?

c# - 防止 "Edit"用户控件上的 CSS 更改?

c# - Outlook 2010 加载项 : how to go through all mail messages?

c# - 建议在 'DTO' 响应/请求中收集 REST/服务设计

c# - mysql语法错误

c# - 绑定(bind) List<string> 到 ComboBox

c# - 将 WinForms UserControl 公开为 ActiveX 控件