【发布时间】:2010-12-13 17:57:39
【问题描述】:
我有一个带有两个ListBoxes 的窗口,它们都绑定到一个XMLDataProvider。 Listbox1 的 SelectedItem 属性双向绑定到 ListBox2 的 SelectedItem 属性。到目前为止一切顺利。
ListBox2 包含一个 Style Trigger,当鼠标悬停在某个项目上时,它会将 IsSelected 设置为 true。由于双向绑定,ListBox1 中的对应项也被选中。当我通过单击在Listbox1 中选择一个项目时,就会出现问题
例如,当我在 ListBox1 中选择“Book 1”,然后将鼠标移到 ListBox2 中的所有项目上时,样式触发器触发时将不再选择项目“Book 1”。一旦我在Listbox1 中选择了一个项目,我就不能再通过将鼠标移到Listbox2 中的相应项目上来选择它。但是,通过鼠标单击选择仍然有效。
有人可以解释这种行为和/或提供解决方案吗?
<Window x:Class="Test.sample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
SizeToContent="WidthAndHeight">
<Window.Resources>
<Style TargetType="ListBox">
<Style.Setters>
<Setter Property="Width" Value="150"/>
<Setter Property="Margin" Value="4"/>
</Style.Setters>
</Style>
<!-- define the XML data source as a resource -->
<XmlDataProvider x:Key="TestData" XPath="/Books">
<x:XData>
<Books xmlns="">
<Book>
<Title>Book 1</Title>
<Author>Mister 1</Author>
</Book>
<Book>
<Title>Book 2</Title>
<Author>Mister 2</Author>
</Book>
<Book>
<Title>Book 3</Title>
<Author>Mister 3</Author>
</Book>
<Book>
<Title>Book 4</Title>
<Author>Mister 4</Author>
</Book>
<Book>
<Title>Book 5</Title>
<Author>Mister 5</Author>
</Book>
<Book>
<Title>Book 6</Title>
<Author>Mister 6</Author>
</Book>
</Books>
</x:XData>
</XmlDataProvider>
</Window.Resources>
<Grid>
<StackPanel Orientation="Horizontal">
<StackPanel>
<Label HorizontalContentAlignment="Center">Listbox 1</Label>
<ListBox x:Name="box1" ItemsSource="{Binding Source={StaticResource TestData}, XPath=Book}"
SelectedItem="{Binding ElementName=box2, Path=SelectedItem, Mode=TwoWay}">
<ListBox.ItemTemplate>
<DataTemplate>
<Label Content="{Binding XPath=Title}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
<StackPanel>
<Label HorizontalContentAlignment="Center">Listbox 2</Label>
<ListBox x:Name="box2" ItemsSource="{Binding Source={StaticResource TestData}, XPath=Book}">
<ListBox.ItemTemplate>
<DataTemplate>
<Label Content="{Binding XPath=Title}"/>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Padding" Value="12"/>
<Setter Property="IsSelected" Value="True"/>
</Trigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
</StackPanel>
</StackPanel>
</Grid>
</Window>
【问题讨论】:
-
+1 提供了一个完整的可运行示例和清晰的解释,抱歉不能帮助你.. :)
标签: wpf xaml select binding listbox