我正在尝试为我的用户控件设置样式。 UserControl位于项目“控件”中,主题位于项目“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>
答案 0 :(得分: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
答案 1 :(得分: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>
并且