2013-11-26 30 views
0

我很難理解爲什麼發生{DependencyProperty.UnsetValue},並且老實說也就是它的意思。我有一個「借用代碼」的例子,它在原始解決方案中很好地工作,但在我的項目中卻不起作用。TemplateBinding給出錯誤DependencyProperty.UnsetValue

有三種樣式定義:

<Style TargetType="Button" BasedOn="{StaticResource {x:Type ButtonBase}}" /> 
<Style TargetType="c:DropDownButton" BasedOn="{StaticResource {x:Type ButtonBase}}" /> 
<Style TargetType="{x:Type ButtonBase}"> 
.... 
<Setter Property="Background" Value="{StaticResource ButtonBrush}" /> 
<Setter Property="Template"> 
    <Setter.Value> 
     <ControlTemplate TargetType="ButtonBase"> 
      <Border x:Name="PART_border" 
        .... 
        Background="{TemplateBinding Background}" 
        Padding="{TemplateBinding Padding}"> 
       <ContentPresenter RecognizesAccessKey="True" 
            VerticalAlignment="{TemplateBinding VerticalContentAlignment}" 
            orizontalAlignment="{TemplateBinding HorizontalContentAlignment}" /> 
      </Border> 
     </ControlTemplate> 
    </Setter.Value> 
</Setter> 

Background="{TemplateBinding Background}"給出了錯誤,用硬編碼的顏色它按預期工作。
當我禁用<!--<Setter Property="Background" Value="{StaticResource ButtonBrush}"/>-->時,也會發生異常,但只有之後應用程序已加載並且可見。這不是很奇怪嗎?

我不明白爲什麼原始項目沒有這個問題。
解決方案是:wpf必須在應用樣式之前找到畫筆。
在我的情況下,我移動了樣式定義之前使用的畫筆。
我明白上面的「奇怪的行爲」,因爲wpf在稍後的時間點應用畫筆,因此在稍後的時間拋出異常。

+2

['DependencyProperty.UnsetValue'](http://msdn.microsoft.com/zh-cn/library/system.windows.dependencyproperty.unsetvalue(v = vs.110).aspx)*指定一個靜態值WPF屬性系統使用該屬性而不是null來指示該屬性存在,但沒有通過屬性系統*設置其值。 – Sheridan

回答

1

如果您的筆刷放置在不同的資源字典中,它確實認識到在編譯時您的應用程序中存在這樣的密鑰,但據我所知,無法保證資源何時應用。

在這種情況下使用一個DynamicResource來解決問題。

+0

好,解決了。觸發您的帖子,我看到我的畫筆順序與原始項目相比有所不同。我的畫筆位於相同的資源字典中,但在使用樣式定義後放置。更改訂單解決了它。 – Gerard