用户控件的样式设置

3

我正在尝试为我的用户控件设置样式。用户控件位于名为“Controls”的项目中,而主题则在名为“MainProject”的项目中。

<UserControl x:Class="Controls.OutputPanel"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        mc:Ignorable="d" 
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        x:Name="OutputControl"> 
   <!-- Style="{DynamicResource UserControlStyle}"> - I cant set the style here because the Resource Dictionary hasn't been defined yet -->

    <UserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/MainProject;component/Themes/MyTheme.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </UserControl.Resources>

    <!-- Now that the Resource Dictionary has been defined I need to set the style -->      

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>

        <TextBox x:Name="textbox" 
                   ScrollViewer.VerticalScrollBarVisibility="Visible"
                   Text="{Binding ElementName=OutputControl, Path=TextProperty}"
                   IsReadOnly="True"
                   Style="{DynamicResource OutputTextBoxStyle}"/>

    </Grid>

</UserControl>

根据我的经验,最好的做法是在应用资源中加载您的资源字典。这样可以使其在应用程序启动时立即可用。 - jjrdk
该项目是一个UserControl库,因此没有App.xaml文件可用于此操作。 - Eamonn McEvoy
2个回答

7

据我所见,那应该是正常工作的。你是否收到任何特殊警告或错误,或者某些样式未被应用?

在设置了Resources之后设置样式,您可以使用以下语法:

<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/MainProject;component/Themes/MyTheme.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</UserControl.Resources>
<UserControl.Style>
    <DynamicResource ResourceKey="UserControlStyle"/>
</UserControl.Style>

如果您在此之后仍然遇到问题,您可以将其与我上传的示例应用进行比较: http://www.mediafire.com/?q1v98huubzw02zb

非常感谢,我看了你的例子,已经搞定了 :) - Eamonn McEvoy

1
你可以创建一个新的资源字典,定义你的样式,然后将其添加到应用程序资源中。
<Window x:Class="WpfApplication1.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:UC="clr-namespace:UserControls;assembly=UserControls">
   <Grid>
      <UC:myUserControl/>
   </Grid>
</Window>


<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:UC="clr-namespace:UserControls;assembly=UserControls">

    <Style TargetType="UC:myUserControl">
       ...
    </Style>
</ResourceDictionary>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接