我有一个ListBox
绑定到一个ObesvableCollection
动态创建的UserControls
.
<ListBox x:Name="myListBox">
<ListBox.Style>
<Style TargetType="{x:Type ListBox}">
<Setter Property="ItemsSource" Value="{Binding userControlsCollection}"/>
....
</Style>
</LIstBox.Style>
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<EventSetter Event="Selector.Selected" Handler="ListBox_Selected"/>
<EventSetter Event="Selector.Unselected" Handler="ListBox_UnSelected"/>
<Setter Property="Background" Value="{DynamicResource DefaultBackground}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
SnapsToDevicePixels="true"
Width="{Binding ActualWidth,RelativeSource={RelativeSource FindAncestor,AncestorType=ListBoxItem,AncestorLevel=1}}"
Height="{Binding ActualHeight,RelativeSource={RelativeSource FindAncestor,AncestorType=ListBoxItem, AncestorLevel=1}}"
/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox>
我想设置所选控件的背景应该是这样的
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="{DynamicResource SelectedBackground}"/>
</Trigger>
</Style.Triggers>
但这样我设置ListBoxItem
Background
它并不会传播用户控件背景......
我现在解决它的方法是使用这样的 Selector.Selected/UnSelected 事件处理程序
private void ListBox_Selected(object sender, RoutedEventArgs e)
{
var item = e.Source as ListBoxItem;
var ctrl= item.Content as myControl;
if (ctrl!= null)
{
ctrl.Background = new SolidColorBrush(DefaultSelectedBackground);
}
}
任何想法都会非常受欢迎