看起來你很困惑XAML的語義。直到你習慣了XAML,它可能有助於將其視爲C#等價物。這主要是你現在在做什麼:
Style BorderStyle = new Style();
Border inlineStyle = new Border { Style = BorderStyle };
Style listBoxItemDefaultStyle = new Style();
listBoxItemDefaultStyle.Setters.Add(new Setter(StyleProperty, inlineStyle));
ListBoxItem item = new ListBoxItem { Style = listBoxItemDefaultStyle };
一個問題是,你要引起某種設定的ListBoxItem的樣式從樣式爲您ListBoxItem的內部二傳手,這當然是遞歸問題。因此,從我們得到的代碼去除多餘的風格:
Style BorderStyle = new Style();
Border inlineStyle = new Border { Style = BorderStyle };
ListBoxItem item = new ListBoxItem { Style = inlineStyle };
這是無效的,因爲它試圖(類型樣式)的樣式屬性設置爲一個Border對象。這基本上是你看到的錯誤的核心。
在這種情況下,您真正想要更改ListBoxItem ControlTemplate以合併您的邊框樣式。這是默認的樣式修改爲使用您的邊框,而不是使用TemplateBindings設置其屬性的標準樣式:
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="HorizontalContentAlignment" Value="{Binding HorizontalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
<Setter Property="VerticalContentAlignment" Value="{Binding VerticalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
<Setter Property="Padding" Value="2,0,0,0"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Border x:Name="Bd" Style="{StaticResource BorderStyle}" Width="200">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/>
</Trigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsSelected" Value="true"/>
<Condition Property="Selector.IsSelectionActive" Value="false"/>
</MultiTrigger.Conditions>
<Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
</MultiTrigger>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
您想要做什麼?你能解釋一下嗎? – Rev 2010-06-29 12:33:01
我想爲listBoxItem創建我自己的樣式。我希望ListBox中的每個Item都具有像上面顯示的Border這樣的樣式 – Polaris 2010-06-29 12:36:34