在下面的代码中,为什么属性IsSelected
设置为的项目没有像单击后一样true
被选中?
ComboBox
ListBox
Button
一旦我点击ComboBox
,选定的项目就会被选中,但不是之前。
xml:
<Window x:Class="WpfApplication1.Desktop.Shell"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="350" Width="525">
<StackPanel>
<ListBox ItemsSource="{Binding Items}">
<ListBox.Resources>
<Style TargetType="ListBoxItem">
<Setter Property="IsSelected"
Value="{Binding Path=IsSelected, Mode=TwoWay}" />
</Style>
</ListBox.Resources>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Label Content="{Binding Txt}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<ComboBox ItemsSource="{Binding Items}">
<ComboBox.Resources>
<Style TargetType="ComboBoxItem">
<Setter Property="IsSelected"
Value="{Binding Path=IsSelected, Mode=TwoWay}" />
</Style>
</ComboBox.Resources>
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Label Content="{Binding Txt}" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<Button Content="Select second item" Click="Button_Click" />
</StackPanel>
</Window>
xml.cs:
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.Windows;
using Microsoft.Practices.Prism.ViewModel;
namespace WpfApplication1.Desktop
{
[Export]
public partial class Shell : Window
{
public class Foo : NotificationObject
{
static int _seq = 0;
string _txt = "Item " + (++_seq).ToString();
public string Txt { get { return _txt; } }
bool _isSelected;
public bool IsSelected
{
get { return _isSelected; }
set
{
_isSelected = value;
RaisePropertyChanged(() => IsSelected);
}
}
}
public ObservableCollection<Foo> Items { get; set; }
public Shell()
{
Items = new ObservableCollection<Foo>();
for (int i = 0; i < 5; i++)
Items.Add(new Foo());
DataContext = this;
InitializeComponent();
}
void Button_Click(object sender, RoutedEventArgs e)
{
Items[1].IsSelected = true;
}
}
}