2

我正在嘗試爲我的用戶控件設置風格。 UserControl是在一個項目「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> 
+0

以我的經驗做的最好的事情是在你的資源字典加載的應用程序資源。這使它在應用程序的開始時可用。 – jjrdk 2011-03-01 11:57:51

+0

該項目是一個UserControlLibrary所以沒有App.xaml文件來做到這一點 – 2011-03-01 12:03:21

回答

6

這應該工作得很好,據我所見。你有沒有得到任何特別的警告或錯誤或做一些風格的部分沒有得到應用?

要設置樣式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

+0

非常感謝,看看你的例子,並得到它的工作:) – 2011-03-01 12:59:00

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> 

而且