if it do ,how should I binding Visibility to ListViewItem's IsSelected Property?
The ListViewItem class provides the container for items displayed in a ListView control. You populate the ListView by adding objects directly to its Items collection or by binding its ItemsSource property to a data source. When items are added to the ListView, a ListViewItem container is created automatically for each item in the collection.
For more info, please refer the Remark of the ListViewItem.
We should be able to use the the SelectionChangedEventArgs.AddedItems
to get a list that contains the items that were selected. We also can use the SelectionChangedEventArgs.RemovedItems
to get a list that contains the items that were unselected.
We can define the IsSelected
property in the Class, the Class should inherit the INotifyPropertyChanged
. In the SelectionChanged
event, we can set the Selected Item and UnSelect Item to the IsSelected property of the Item.
For example:
public class Item : INotifyPropertyChanged
{
private string _title;
private bool _isSelected;
public string Title
{
get { return _title; }
set
{
_title = value;
RaisePropertyChanged("Title");
}
}
public bool IsSelected
{
get { return _isSelected; }
set
{
_isSelected = value;
RaisePropertyChanged("IsSelected");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}
Then we can bind the Visibility
to the IsSelected
without converting the type.
For example:
<ListView Name="MyListView" SelectionChanged="MyListView_SelectionChanged">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Title}" Visibility="{Binding IsSelected, Mode=OneWay}"></TextBlock>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
The code behind:
private ObservableCollection<Item> Items;
public MainPage()
{
this.InitializeComponent();
Items = new ObservableCollection<Item>();
Items.Add(new Item());
Items[0].Title = "Title1";
Items.Add(new Item());
Items[1].Title = "Title2";
MyListView.ItemsSource = Items;
}
private void MyListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
foreach (Item item in e.RemovedItems)
{
item.IsSelected = false;
}
foreach (Item item in e.AddedItems)
{
item.IsSelected = true;
}
}