新建一个名为"Dictionary1"的资源字典:<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style x:Key="aa">
        <Setter Property="Control.Template">
            <Setter.Value>
                <ControlTemplate>
                    <Border Background="Red">
                        <ContentPresenter />
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>
在项目中使用:<Window x:Class="WPF3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="800" Width="1105">
    <Window.Resources>
        <Style x:Key="aa">
            <Setter Property="Control.Template" >
                <Setter.Value>
                    <ControlTemplate>
                        <Grid>
                            <Control Style="{DynamicResource aa}">
                                <Control.Resources>
                                   <ResourceDictionary Source="pack://application:,,,/WPF3;component/Dictionary1.xaml"/> 
                                </Control.Resources>
                            </Control>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
</Window>第二段代码为什么会出现这样的错误:无法将类型为“System.Windows.ResourceDictionary”的对象强制转换为类型“Microsoft.Expression.Markup.DocumentModel.DocumentCompositeNode”

解决方案 »

  1.   

    你把Dictionary1.xaml放在app.xaml里:
     <Application.Resources>
            <ResourceDictionary Source="./Dictionary1.xaml"/>
     </Application.Resources>在MainWindow里<Window.Resources>
            <Style x:Key="aa">
                <Setter Property="Control.Template" >
                    <Setter.Value>
                        <ControlTemplate>
                            <Grid>
                                <Control Style="{DynamicResource aa}"/> 
                            </Grid>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </Window.Resources>
      

  2.   

    类型不对,用TypeConvert在后台做强制转换。
      

  3.   

    什么类型不对啊?都是Control啊
      

  4.   

    你就不能换个名字吗?都用aa都不知道访问自己的aa还是外面的aa了。
    写在app.xaml里面是很直接的注册方法,因为程序入口就在那个app.xaml,因此所有注册的样式都能有效。
    如果想写在其他文件里,并且要让程序能加载它,就必须遵循WPF的规则来写,不能随便命名和存放文件,参考,在Style & FrameworkElement章节里有说明,如果你基础不够,建议看全,这是一篇非常好的文章。