![](/img/trans.png)
[英]WPF: Get a ListBoxItem as CheckBox with a Template Style to synchronize with IsSelected
[英]MouseOver and IsSelected events for ListBoxItem in WPF
我想讓ListBoxItem觸發兩個事件,這些事件可以從包含ListBox的外部usercontrol中捕獲。 這是到目前為止我得到的:
<ListBox
Background="Black"
Selected="listbox_selected"
x:Name="listBox">
<ListBox.Resources>
<Style TargetType="ListBoxItem" BasedOn="{StaticResource {x:Type ListBoxItem}}">
<Style.Triggers>
<DataTrigger Binding="{Binding IsMouseOver,RelativeSource={RelativeSource Self}}"
Value="True">
<Setter Property="IsSelected" Value="True" />
</DataTrigger>
</Style.Triggers>
</Style>
</ListBox.Resources>
</ListBox>
現在,這稱為我的listbox_Selected事件。 我想要的是在IsMouseOver時調用不同的事件或屬性。 為了清楚起見,我知道如何更改ListBoxItem本身的背景/前景或其他屬性。 但是我想換個祖父母。
您已經有了該事件...只要我們不處理后代樹中任何地方的“ Selection”事件,就可以在任何祖先處理來自ListBoxItem
類的靜態路由事件,該事件稱為“ Selected”(還有“ UnSelected”)。
<Window x:Class="...."
...
ListBoxItem.Selected="OnListBoxSelected">
<Grid>
<ListBox ItemsSource="{Binding Employees}"
DispalyMemberPath="Name"
selectedValuePath="ID" >
<ListBox.Resources>
<Style TargetType="ListBoxItem"
BasedOn="{StaticResource
{x:Type ListBoxItem}}">
<Style.Triggers>
<DataTrigger Binding="{Binding IsMouseOver,
RelativeSource={RelativeSource
Self}}"
Value="True">
<Setter Property="IsSelected"
Value="True" />
</DataTrigger>
</Style.Triggers>
</Style>
</ListBox.Resources>
</ListBox>
</Grid>
</Window>
並在后面的代碼中...
private void OnListBoxSelected(object sender, RoutedEventArgs e)
{
var window = sender as Window;
var listBoxItem = e.OriginalSource as ListBoxItem;
var selectedItem = listBoxItem.DataContext;
}
希望這可以幫助...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.