简介:
修改ListBox 选中Item后的效果,通过显式设置 ItemContainerStyle 属性。
介绍:
ItemContainerStyle | 获取或设置应用于为每个项生成的容器元素的 Style。 |
使用:
更改选中项背景色。
添加提示。
public class PersonNP : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string name;
public string Name
{
get { return name; }
set { name = value; Notify(); }
}
private string id;
public string Id
{
get { return id; }
set { id = value;Notify(); }
}
private void Notify([CallerMemberName]string obj ="")
{
if (PropertyChanged != null)
{
this.PropertyChanged (this, new PropertyChangedEventArgs(obj));
}
}
}
public MainWindow()
{
InitializeComponent();
ObservableCollection<PersonNP> ocP = new ObservableCollection<PersonNP>() {
new PersonNP(){Id = "1", Name="test1"},
new PersonNP(){Id = "2", Name="test2"},
};
listBx.ItemsSource = ocP;
}
<Window.Resources>
<ToolTip x:Key="InforTip">
<StackPanel Orientation="Horizontal">
<TextBlock Text="Id:" />
<TextBlock Text="{Binding Path=Id}"/>
<TextBlock Text=" Name:" />
<TextBlock Text="{Binding Path=Name}"/>
</StackPanel>
</ToolTip>
<Style TargetType="ListBox" x:Key="lbxS">
<Style.Setters>
<Setter Property="FontSize" Value="20"/>
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<Border Background="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBoxItem}},Path=Background}"
Margin="5 5 5 5" CornerRadius="5" BorderThickness="2" BorderBrush="LimeGreen">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Text="{Binding Id}"/>
<TextBlock Text="{Binding Name}" Grid.Row="1"/>
</Grid>
</Border>
</DataTemplate>
</Setter.Value>
</Setter>
<Setter Property="ItemContainerStyle">
<Setter.Value>
<Style TargetType="ListBoxItem">
<Style.Triggers>
<Trigger Property="ListBoxItem.IsSelected" Value="True">
<Setter Property="ListBoxItem.Background" Value="Green"/>
</Trigger>
<Trigger Property="ListBoxItem.IsMouseOver" Value="True">
<Setter Property="ListBoxItem.ToolTip" Value="{Binding Source={StaticResource InforTip}}" />
</Trigger>
</Style.Triggers>
</Style>
</Setter.Value>
</Setter>
</Style.Setters>
</Style>
</Window.Resources>
<Grid>
<StackPanel>
<ListBox x:Name="listBx" Style="{StaticResource lbxS}" ></ListBox>
</StackPanel>
</Grid>
效果: