2011-09-14 29 views
1

在windows.resource中使用下一代碼塊。樣式中的Stackpanel

<Style TargetType="Button" x:Key="l1" > 
    <Setter Property="Button.Effect" > 
    <!--<Setter Property="BitmapEffect">--> 
     <Setter.Value> 
      <DropShadowEffect /> 
     </Setter.Value> 
    </Setter> 
    <Setter Property="Content" > 
     <Setter.Value > 
      <StackPanel Orientation="Horizontal"> 
       <Image Source="Resources\find.bmp" Stretch="Uniform" ></Image> 
       <TextBlock>Find</TextBlock> 
      </StackPanel> 
     </Setter.Value> 
    </Setter> 
</Style> 

它僅適用於一個按鈕,但只要我在運行時它APLY到第二個按鈕的錯誤發生。

<Button Height="23" HorizontalAlignment="Left" Margin="322,25,0,0" Name="Button18" VerticalAlignment="Top" Width="75" Style="{StaticResource l1}" /> 
<Button Height="23" HorizontalAlignment="Left" Margin="586,37,0,0" Name="Button19" VerticalAlignment="Top" Width="75" Style="{StaticResource l1}" /> 

解決此問題的任何解決方案?

+2

什麼錯誤,你實際上得到? –

回答

0

您不能直接用這種方式設置ContentControlContent。原因在於Content設置器中的StackPanel(僅指一個)與該樣式適用的所有按鈕都是相同的實例;然而,這是不允許的(並且可能導致你獲得元素已經是另一個元素的例外)。

相反,你應該設置ContentTemplate屬性:

<Setter Property="ContentTemplate"> 
    <Setter.Value> 
     <DataTemplate> 
      <StackPanel Orientation="Horizontal"> 
       <Image Source="Resources\find.bmp" Stretch="Uniform" ></Image> 
       <TextBlock>Find</TextBlock> 
      </StackPanel> 
     </DataTemplate> 
    </Setter.Value> 
</Setter> 

這工作,因爲現在是一個新的視覺樹枝將作爲模板的每個實例被創建(即會有許多StackPanel小號等作爲你有按鈕)。

0

您不能通過類似的風格設置控件的內容(至少不是兩次)。

你應該使用模板來發送的內容,就像這樣:

<DataTemplate x:Key="buttonTemplate"> 
     <StackPanel Orientation="Horizontal"> 
      <Image Source="Resources\find.bmp" Stretch="Uniform" ></Image> 
      <TextBlock>Find</TextBlock> 
     </StackPanel> 
    </DataTemplate> 
    <Style TargetType="Button" x:Key="l1" > 
     <Setter Property="Button.Effect" > 
      <Setter.Value> 
       <DropShadowEffect /> 
      </Setter.Value> 
     </Setter> 
     <Setter Property="ContentTemplate" Value="{StaticResource buttonTemplate}" /> 
    </Style>