我正在尝试将 ListViewItem 的 IsSelected 属性绑定到 ViewModel 中的属性。它在 WPF 中运行良好,但在 Windows RT 中,IsSelected 属性永远不会被设置。
public class Item : INotifyPropertyChanged
{
private readonly string name;
private bool isSelected;
public event PropertyChangedEventHandler PropertyChanged;
public bool IsSelected
{
get { return isSelected; }
set { isSelected = value; RaisePropertyChanged("IsSelected"); }
}
public string Name { get { return name; } }
public Item(string name)
{
this.name = name;
}
protected void RaisePropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
handler.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class ViewModel
{
private readonly ObservableCollection<Item> items = new ObservableCollection<Item>(Enumerable.Range(0, 10).Select(p => new Item(p.ToString())));
public ObservableCollection<Item> Items { get { return items; } }
}
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
DataContext = new ViewModel();
}
}
xml:
<StackPanel Orientation="Horizontal">
<ListView ItemsSource="{Binding Path=Items}" SelectionMode="Multiple">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="IsSelected" Value="{Binding Path=IsSelected, Mode=TwoWay}"/>
</Style>
</ListView.ItemContainerStyle>
</ListView>
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Name}"/>
</DataTemplate>
</ListView.ItemTemplate>
</StackPanel>
我可以单击屏幕上的项目,但 IsSelected 属性没有传播到 ViewModel。任何想法为什么?