看起来你很困惑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