How do I create a two-way link the SelectedItem property of a ListView?
I've recently taken over a MVVM project started by someone who's now left the company; It's my first time using WPF, but by the looks of it, it was his first time using both WPF and OOP...
Anyway, I've got a ListView in the XAML, and I've got a collection class which doesn't currently contain a "SelectedItem" property.
Can someone tell me what code I need to put in to link the SelectedItem of the ListView to the as-yet-unwritten SelectedItem property of my collection, and then what code I need to开发者_StackOverflow put in so that the SelectedItem of the collection links back to the ListView?
Apologies for the homework-level question, but the code I'm working with is such a nightmare that I can't yet wrap my head around "how to write WPF?" at the same time as "how do I rewrite this coding horror as OOP?" so if someone can supply me with some example code, I can work on inserting it into the nightmare...
You could use WPF binding to perform your task. Excuse me the code will be in C#, but it shouldn't be hard to understand and to adapt in VB.NET ;) :
In Xaml, Your binding must use the TwoWay Mode because you want that any UI update is reflected on the viewmodel.
<ListView SelectedItem="{Binding SelectedItem, Mode=TwoWay}" ItemsSource="{Binding MyObjects}"/>
Your ViewModel need to implement INotifyPropertyChanged in order for the WPF Binding system to be notified of property changes on the ViewModel.
public class MyViewModel: INotifyPropertyChanged
{
private MyObj selectedItem;
public MyObj SelectedItem
{
get{return this.selectedItem;}
set
{
if(value!=selectedItem)
{
selectedItem = value;
RaisePropertyChanged("SelectedItem");
}
[... your collection....]
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propertyName)
{
var propertyChanged = this.PropertyChanged;
if(propertyChanged!=null)
propertyChanged(new PropertyChangedEventArgs(propertyName));
}
Lv.selected item will return you a reference to the object in the collection represented by the visible selected item if you have done your databinding correctly.
dim s as List( of MyObj)
ctype(ListVeiw1.SelectedItem,MyObj).MyProp
精彩评论