2012-07-02 29 views
0

我有這樣的風格:設定值

<Style x:Key="SelectableListBoxItemStyle" TargetType="{x:Type ListBoxItem}"> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="{x:Type ListBoxItem}"> 

       <Border Background="Transparent" 
         BorderBrush="{TemplateBinding BorderBrush}" 
         CornerRadius="4" 
         BorderThickness="2" 
         x:Name="IconBorder" 
         Margin="4,2,4,2"> 
        <ContentPresenter/> 
       </Border> 

       <ControlTemplate.Triggers> 
        <Trigger Property="IsSelected" Value="true"> 
         <Setter TargetName="IconBorder" 
           Property="BorderBrush" 
           Value="Blue" /> 
        </Trigger> 
       </ControlTemplate.Triggers> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

我的問題是,我不知道在列表框設置其屬性,消耗我的風格的時候,這樣它的邊界是ListBoxItems會最終得到所需的邊框刷。我也想在我的風格中爲其他邊框筆畫做這項工作。

我希望能夠擁有兩個具有相同風格但不同邊框顏色的列表框。我有這樣的一個列表框中:

<ListBox 
     ItemsSource="{Binding SelectedProduct.Pictures}" 
     SelectedItem="{Binding SelectedSet, Mode=TwoWay}" 
     ItemContainerStyle="{StaticResource ResourceKey= SelectableListBoxItemStyle}"> 
    </ListBox> 

Update..I嘗試這樣做:

<ListBox 
     ItemsSource="{Binding SelectedProduct.Pictures}" 
     SelectedItem="{Binding SelectedSet, Mode=TwoWay}"> 

      <ListBox.ItemContainerStyle> 
       <Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource SelectableListBoxItemStyle}"> 
        <Setter TargetName="IconBorder" Property="BorderBrush" Value="Green" /> 
       </Style> 
      </ListBox.ItemContainerStyle> 

     </ListBox> 

但是,我得到: 錯誤8 targetName屬性不能在風格二傳手設定。

回答

1

而不是使用一個TemplateBinding的你應該嘗試使用相對源綁定。

BorderBrush="{Binding RelativeSource={RelativeSource FindAncestor, 
             AncestorType={x:Type Listbox}}, 
             Path=BorderBrush}" 

如果你想比,對於ListBox定義不同的邊框,那麼你就需要一個畫筆資源添加到您的ResourceDictionary並應用來代替:

<Listbox.Resources> 
    <SolidColorBrush x:Key="MyListBoxItemBorderBrush" Color="Red"/> 
<Listbox.Resources> 

,然後在你的模板:

BorderBrush="{StaticResource MyListBoxItemBorderBrush}" 

如果你需要某些項目有不同的邊界,那麼你需要看看StyleSelector

+0

感謝您的回答。請參閱我已經將列表框的項目容器樣式設置爲粘貼在我的問題中的「SelectableListBoxItemStyle」。問題出在'BorderBrush =「{TemplateBinding BorderBrush}」。當我在xaml中使用Style時,如何設置* this? IE瀏覽器。我應該在列表框上設置哪些屬性,以便我的ListBoxItem的邊框最終具有設置​​的邊框畫筆? –

+0

再次感謝。第二個工作,但現在我的列表框需要有相同的BorderBrush,因爲它是ListBoxItems,這不是很好。我編輯我的問題添加更新,也許你可以修復:) –

+0

哦,一個不錯的!資源竅門釘住了它。非常感謝你 :) –

0

我不是100%確定,但我認爲你可能需要一個自定義控件。至少我知道你可以用自定義控件來做到這一點!

如果您創建一個自定義控件,從包含此樣式的ListBox開始,然後創建一個附加屬性(如ItemBorderColor),您可以綁定到您的邊框的BorderColor(實際上,選擇效果,您可能需要在ControlTemplate()上創建一個觸發器,該觸發器基於「IsSelected」屬性將「ItemBorderColor」值應用於邊框的BorderColor)。

有可能是一個純粹的XAML的方式來做到這一點,但我不知道它....

+0

是的,這將工作。我會堅持下去,也許會彈出一些東西。如果這只是一種風格無法完成,這將是一個恥辱...... –

+0

看看本傑明的答案,它確認您將需要某種內存容器(或屬性)來存儲「ItemBorderColor」的值。這是(我認爲)XAML不足之處,因爲它不會讓你「創造」一種風格的新物業。 雖然我可能錯了... – JFTxJ