如何加载自定义staticresource

时间:2015-05-11 04:42:26

标签: c# wpf xaml

我要2个文件: ButtonStyle.xaml和 ConstantsStyle.xaml

在App.xaml中,我将初始化

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

    <Thickness x:Key="GenericButtonStylePadding">0,7</Thickness>

</ResourceDictionary>

文件ConstantsStyle.xaml

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:vsm="clr-namespace:System.Windows;assembly=System.Windows"
    xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit" 
    xmlns:usercontrols="clr-namespace:Zalo.UserControls">

    <Style x:Key="GenericButtonStyle" TargetType="Button">
        <Setter Property="VerticalContentAlignment" Value="Center"/>
        <Setter Property="HorizontalContentAlignment" Value="Center"/>
        <Setter Property="Padding" Value="{StaticResource GenericButtonStylePadding}"/>
   </Style>

</ResourceDictionary>

文件ButtonStyle.xaml

<figure>

App崩溃运行时。因为找不到具有Name / Key GenericButtonStylePadding ???

的资源

我如何正确运行应用程序???请帮帮我

1 个答案:

答案 0 :(得分:1)

尝试使用DyanamicResource而不是StaticResource

<Style x:Key="GenericButtonStyle" TargetType="Button">
        <Setter Property="VerticalContentAlignment" Value="Center"/>
        <Setter Property="HorizontalContentAlignment" Value="Center"/>
        <Setter Property="Padding" Value="{DynamicResource GenericButtonStylePadding}"/>
   </Style>

编辑: 你可以测试一件事。将另一个常量添加到Constant.XAML

<Brush x:Key="BGBrush">Black</Brush>

尝试在ButtonStyle.XAML中使用它

<Style x:Key="GenericButtonStyle" TargetType="Button">
        <Setter Property="VerticalContentAlignment" Value="Center"/>
        <Setter Property="HorizontalContentAlignment" Value="Center"/>
        <Setter Property="Width" Value="200"></Setter>
        <Setter Property="Background" Value="{StaticResource BGBrush}"></Setter>
    </Style>

查看按钮背景是否变为黑色。 如果颜色正在改变,那么尝试除厚度之外的其他东西。