如何在用户控件xaml中使用应用程序资源

时间:2011-12-29 20:41:24

标签: wpf xaml user-controls

我有一个包含一些资源的app.xml,例如:

<Application.Resources>
    <con:EnumToVisibilityConverter x:Key="EnumToVisibilityConverter" />
    <con:NegateBoolConverter x:Key="NegateBoolConverter" />
    <Style TargetType="FrameworkElement" x:Key="BaseStyle">
        <Setter Property="HorizontalAlignment" Value="Stretch" />
        <Setter Property="VerticalAlignment" Value="Stretch" />
        <Setter Property="Margin" Value="3"/>
        <Setter Property="Width" Value="120"/>
        <Setter Property="Height" Value="25" />
    </Style>
    <Style TargetType="CheckBox" BasedOn="{StaticResource BaseStyle}">
    </Style>
    <Style TargetType="DatePicker" BasedOn="{StaticResource BaseStyle}">
    </Style>
    <Style TargetType="TextBox" BasedOn="{StaticResource BaseStyle}">

    </Style>
    <Style TargetType="Label"  BasedOn="{StaticResource BaseStyle}">

    </Style>

    <Style TargetType="Button" BasedOn="{StaticResource BaseStyle}">
        <Setter Property="Width" Value="75" />
        <Setter Property="Height" Value="23" />
        <Setter Property="Margin" Value="5,2,2,5" />
        <Setter Property="HorizontalAlignment" Value="Left" />
        <Setter Property="VerticalAlignment" Value="Top" />
    </Style>

</Application.Resources>

我想在我的用户控件xaml中使用它们,如下所示:

 <UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="App.xaml" />
        </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
 </UserControl.Resources>

由于我的用户控件xaml在View目录中,系统不接受上面提到的语法,并抱怨它无法找到view / app.xaml。如何添加路径以便它可以找到它?

1 个答案:

答案 0 :(得分:1)

你不需要这样做。应用程序资源遍布整个应用程序,因此您只需要在xaml中执行此操作:

Style="{StaticResource BaseStyle}"

或者在C#中(在你的控件代码中):

Style baseStyle = (Style)this.FindResource("BaseStyle");