Xamarin forms ListView item dynamic update to GUI - c#

I've created a ListView in Xamarin form and bind to Observable collection in view model, adding item dynamically to ListView is working fine by calling OnPropertyChanged event.
But after getting status update from service I'm updating corresponding ListView item status and calling OnPropertyChanged event as well as re-assigining the ListView items to it but didn't get updated GUI properly sometimes working and some times not.
Below is the sample code that I've done.
<ListView Grid.Row="3" HasUnevenRows="True" ItemsSource="{Binding ServiceList}" IsPullToRefreshEnabled="True" SeparatorColor="Black">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Vertical" Spacing="4" Padding="5" BackgroundColor="LightGray">
<Label Text="{Binding OperationStatus, Converter={x:Static local:StatusMessageConverter.Default}}" FontSize="13" FontAttributes="Bold" TextColor="White" BackgroundColor="DarkCyan" />
<Label Text="{Binding Operation}" FontSize="10" Margin="10,0,0,0" />
<Label Text="{Binding OperationType}" FontSize="10" Margin="10,0,0,0" />
<Label Text="{Binding OperationStatus}" LineBreakMode="WordWrap" IsVisible="{Binding CanStatusVisible}" FontSize="10" Margin="10,0,0,0" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
public class ServiceViewModel : INotifyPropertyChanged
{
public ObservableCollection<ServiceItem> ServiceList
{
get
{
return _serviceList;
}
set
{
_serviceList = value;
OnPropertyChanged("ServiceList");
}
}
var tempList = new ObservableCollection<ServiceItem>();
tempList = ServiceList;
var targetItem = from item in tempList
where item.UniqueId == uniqueId
select item;
if (targetItem.Any())
{
var resultItem = targetItem.FirstOrDefault();
resultItem.CanStatusVisible = true;
resultItem.OperationStatus = string.Format("{0}: {1}", "Status Message", resultMessage);
}
ServiceList = null;
ServiceList = tempList;
OnPropertyChanged("ServiceList");
}
public class ServiceItem
{
public string UniqueId { get; set; }
public string Operation { get; set; }
public string OperationType { get; set; }
public string OperationStatus { get; set; }
public string StatusMessage { get; set; }
public bool CanStatusVisible { get; set; }
}

See to it that your model class inherits from INotifyPropertyChangedinterface(as mentioned in the above comments).
public class ServiceItem :INotifyPropertyChanged
{
private string uniqueId,operation,operationType,operationStatus,statusMessage;
private bool statusVisible;
public string UniqueId { get { return uniqueId; } set { uniqueId= value; RaisePropertyChanged(nameof(UniqueId)); } }
public string Operation { get { return operation; } set { operation= value; RaisePropertyChanged(nameof(Operation)); } }
public string OperationType { get { return operationType; } set { operationType= value; RaisePropertyChanged(nameof(OperationType)); } }
public string OperationStatus { get { return operationStatus; } set { operationStatus= value; RaisePropertyChanged(nameof(OperationStatus)); } }
public string StatusMessage { get { return statusMessage; } set { statusMessage= value; RaisePropertyChanged(nameof(StatusMessage)); } }
public bool CanStatusVisible { get { return statusVisible; } set { statusVisible= value; RaisePropertyChanged(nameof(CanStatusVisible )); } }
}
Then your ViewModel code should look something like this:
var tempList = new ObservableCollection<ServiceItem>();
tempList = ServiceList;
var targetItem = from item in tempList
where item.UniqueId == uniqueId
select item;
if (targetItem.Any())
{
var resultItem = targetItem.FirstOrDefault();
resultItem.CanStatusVisible = true;
resultItem.OperationStatus = string.Format("{0}: {1}", "Status Message", resultMessage);
}
ServiceList = null;
ServiceList = tempList;
Once you do these changes your code should work

--- To clarify my comment on FreakyAli's good answer ---
The essential part of FreakyAli's answer is the first code snippet:
public class ServiceItem :INotifyPropertyChanged
...
Once that is done, the other code in question can be greatly simplified. I think (though I have not tested) that you can replace all the code Ali shows under "Then your ViewModel code should look something like this:" with:
ServiceItem resultItem = ServiceList.Where(item => item.UniqueId == uniqueId).FirstOrDefault();
if (resultItem != null)
{
resultItem.CanStatusVisible = true;
resultItem.OperationStatus = string.Format("{0}: {1}", "Status Message", resultMessage);
}
That is, it is not necessary to create a temp list, nor to manipulate ServiceList. When you change the property of a ServiceItem, that property's RaisePropertyChanged will trigger the needed display refresh.

Related

How can I have the respective object in a CollectionView?

I'm trying to use a dynamically created layout using CollectionView to show a series of properties of a class, all based on a list and I want to make it so one of the properties is a Combobox. How do I know what object the ComboBox needs to refer to?
Here is my CollectionView:
<CollectionView x:Name="taskList">
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="models:Task">
<VerticalStackLayout Margin="15">
<Entry Text="{Binding name}" IsReadOnly="True" />
<Entry Text="{Binding departmentsString}" IsReadOnly="True"/>
<HorizontalStackLayout>
<inputs:SfComboBox BackgroundColor="Black" TextColor="Green" DropDownIconColor="Green"/>
<Entry Text="{Binding deadline}" IsReadOnly="True" />
<Entry Text="{Binding author.fullName}" IsReadOnly="True"/>
</HorizontalStackLayout>
<Entry Text="{Binding description}" IsReadOnly="True" />
</VerticalStackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
It has its ItemsSource declared like this:
taskList.ItemsSource = tasks;
tasks being:
ObservableCollection<Classes.Task> tasks { get; set; }
Here is the Task class:
public class Task
{
public Task(string name, List<string> departments, Status status, DateOnly deadline, Employee author, string description)
{
this.name = name;
this.departments = departments;
this.status = status;
this.deadline = deadline;
this.author = author;
this.description = description;
}
public string name { get; private set; }
public List<string> departments { get; private set; } = new List<string>();
public string departmentsString
{
get
{
string _ = "";
foreach (var department in departments)
{
_ += department + (department == departments.Last() ? "": ", ");
}
return _;
}
}
public Status status { get; private set; }
public DateOnly deadline { get; private set; }
public Employee? author { get; set; }
public string description { get; private set; }
public List<Employee> employees { get; private set; } = new List<Employee>();
public void AddEmployee(Employee employee)
{
if (departments.Contains(employee.department))
{
employees.Add(employee);
}
}
}
How do I make it so I can determine the instance of the class Task depending on which ComboBox I change?
Here is what the UI looks like:
Trying to bind the combobox to the Status property
You can try to set a data list for property ItemsSource of SfComboBox and bind a field to property SelectedItem of SfComboBox.
Suppose you would bind departments to the ItemsSource of SfComboBox, then we need to add a field (e.g. SelectedItem) to bind to property SelectedItem of SfComboBox:
Then we need to implement interface INotifyPropertyChanged for MyTask.cs and add field SelectedItem.(To prevent conflicts with the Task class in my project, I named it MyTask)
//add SelectedItem here
private string _selectedItem;
public string SelectedItem
{
get => _selectedItem;
set => SetProperty(ref _selectedItem, value);
}
The whole code of MyTask
public class MyTask: INotifyPropertyChanged
{
public MyTask(string name, List<string> departments, int status, DateTime deadline, Employee author, string description)
{
this.name = name;
this.departments = departments;
this.status = status;
this.deadline = deadline;
this.author = author;
this.description = description;
}
//add SelectedItem here
private string _selectedItem;
public string SelectedItem
{
get => _selectedItem;
set => SetProperty(ref _selectedItem, value);
}
bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
{
if (Object.Equals(storage, value))
return false;
storage = value;
OnPropertyChanged(propertyName);
return true;
}
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
public string name { get; set; }
public List<string> departments { get; private set; } = new List<string>();
public string departmentsString
{
get
{
string _ = "";
foreach (var department in departments)
{
_ += department + (department == departments.Last() ? "" : ", ");
}
return _;
}
}
public int status { get; private set; }
public DateTime deadline { get; private set; }
public Employee? author { get; set; }
public string description { get; private set; }
public List<Employee> employees { get; private set; } = new List<Employee>();
public void AddEmployee(Employee employee)
{
if (departments.Contains(employee.department))
{
employees.Add(employee);
}
}
}
Then we can use like this:
<editors:SfComboBox BackgroundColor="Black" TextColor="Green"
DropDownIconColor="Green"
WidthRequest="250"
ItemsSource="{Binding departments}"
SelectedItem="{Binding SelectedItem}"
/>
Note:
Then if we change the option of SfComboBox , the value of SelectedItem will also update automatically.

Xamarin list of RadioBox set GroupName from view model

All the examples for RadioButtons I've found so far have the values hard-coded in the xaml for the page. I'm looking to feed a list of strings (for now) from a database and running into an issue with the GroupName.
My data template for a radio display type:
<DataTemplate x:Key="RadioTemplate">
<StackLayout>
<Label
Text="{Binding Name}"
Style="{StaticResource LabelStyle}">
</Label>
<ListView ItemsSource="{Binding Choices.Choices}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<RadioButton Value="{Binding}"
Content="{Binding}"
GroupName="someGroupName"
CheckedChanged="OnRadioChanged">
</RadioButton>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</DataTemplate>
MainPageViewModel.cs
using System;
using System.Collections.ObjectModel;
using System.Windows.Input;
using Xamarin.Forms;
using FieldDataTemplateSelectorSample.Validations;
namespace FieldDataTemplateSelectorSample
{
public class MainPageViewModel : ValidationViewModelBase
{
public MainPageViewModel()
{
_fields = new ObservableCollection<FieldViewModel>();
}
private ObservableCollection<FieldViewModel> _fields;
public ObservableCollection<FieldViewModel> Fields
{
get { return _fields; }
set
{
_fields = value;
RaisePropertyChanged();
}
}
private bool _showValidationSummary;
public bool ShowValidationSummary
{
get { return _showValidationSummary; }
set
{
_showValidationSummary = value;
RaisePropertyChanged();
}
}
ICommand _submitCommand;
public ICommand SubmitCommand
{
get => _submitCommand ?? (_submitCommand = new Command(ValidateAndSave));
}
private void ValidateAndSave(object obj)
{
ValidateAll();
if (ErrorStateManager.HasError)
{
ShowValidationSummary = true;
}
else
{
ShowValidationSummary = false;
}
}
}
}
using System.Collections.Generic;
using Xamarin.Forms;
using FieldDataTemplateSelectorSample.Validations;
namespace FieldDataTemplateSelectorSample
{
public class FieldViewModel : ValidationViewModelBase
{
public FieldViewModel()
{
_choices = new ChoiceViewModel();
}
private string _value;
public long Id { get; set; }
public string Name { get; set; }
public string Title { get; set; }
public string Code { get; set; }
public string Value
{
get
{
return _value;
}
set
{
_value = value;
RaisePropertyChanged();
Validate();
}
}
public string PlaceholderText { get; set; }
public int SortOrder { get; set; }
public string DisplayType { get; set; }
public bool IsReadOnly { get; set; }
public bool IsEnabled { get; set; }
private ChoiceViewModel _choices;
public ChoiceViewModel Choices
{
get
{
return _choices;
}
set
{
_choices = value;
RaisePropertyChanged();
}
}
void OnChoicesRadioButtonCheckedChanged(object sender, CheckedChangedEventArgs e)
{
// what else do we need to do? Update value?
RaisePropertyChanged();
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace FieldDataTemplateSelectorSample
{
public class ChoiceViewModel
{
public ChoiceViewModel()
{
Choices = new List<string>();
}
public string Code { get; set; }
public List<string> Choices { get; set; }
}
}
As long as I hard-code the GroupName for the RadioButton in the ViewCell, everything works but that I'll end up with one group name for every single radio button on the page. I've tried adding the property to the StackLayout in the template:
<StackLayout RadioButtonGroup.GroupName="someGroup">
and taking it out out of the RadioButton but when I put a breakpoint in OnRadioChanged, the GroupName comes in as null.
I'd like to use the Code property in the ChoiceViewModel as the group name but haven't gotten the relative binding correct yet. Any help with the binding or different way to do the DataTemplate is appreciated.
you could use a bindable StackLayout which will give you more control over the containter
<StackLayout>
<Label Text="{Binding Name}" Style="{StaticResource LabelStyle}" />
<StackLayout RadioButtonGroup.GroupName="{Binding Name}"
BindableLayout.ItemsSource="{Binding Choices.Choices}" >
<BindableLayout.ItemTemplate>
<DataTemplate>
<ViewCell>
<RadioButton Value="{Binding}" Content="{Binding}"
CheckedChanged="OnRadioChanged" />
</ViewCell>
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
</StackLayout>

Grouped Collection View list not displaying, possible Binding error

I just began working with the MVVM layout and I cannot seem to display anything in my collectionView List. I believe it's my binding, unfortunately I don't really understand how I am supposed to bind a grouped list + the ViewModel. I read to bind to the path no the source, but I'm pretty sure I am doing this incorrectly. I have checked to see if I am even getting shares to load and I am, they're just not displaying.
Model -- Share
[JsonProperty("iSpottedID")]
public int ID { get; set; }
[JsonProperty("sShoppingList")]
[MaxLength(255)]
public string ShoppingName { get; set; }
[JsonProperty("dtInfoUpdate")]
[MaxLength(20)]
public string CreateDate { get; set; }
[JsonProperty("iProductID")]
public int ProductID { get; set; }
[Indexed]
[JsonProperty("sLocation")]
[MaxLength(255)]
public string LocationName { get; set; }
[JsonProperty("tvCardJson")]
public string JsonString { get; set; }
ViewModel -- SharesViewModel
public class SharesViewModel : BaseViewModel
{
#region Properties
private int _id;
public int ID
{
get { return _id; }
set
{
SetValue(ref _id, value);
OnPropertyChanged(nameof(ID));
}
}
private string _longName;
public string LongName
{
get { return _longName; }
set
{
SetValue(ref _longName, value);
OnPropertyChanged(nameof(LongName));
}
}
private string _date;
public string CreateDate
{
get{ return _date;}
set
{
SetValue(ref _date, value);
OnPropertyChanged(nameof(CreateDate));
}
}
private int _prodID;
public int ProductID
{
get { return _id; }
set
{
SetValue(ref _prodID, value);
OnPropertyChanged(nameof(ProductID));
}
}
private string _json;
public string JsonString
{
get { return _json; }
set
{
SetValue(ref _json, value);
OnPropertyChanged(nameof(JsonString));
}
}
private string _location;
public string LocationName
{
get { return _location; }
set
{
SetValue(ref _location, value);
OnPropertyChanged(nameof(LocationName));
}
}
//ADD-ONS
public string Address
{
get
{
if (!string.IsNullOrEmpty(JsonString))
{
var jsonDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonString);
if (jsonDict.ContainsKey("address"))
if (jsonDict["address"] != "")
return jsonDict["address"];
}
return null;
}
}
private ImageSource _imageLink;
public ImageSource ImageLink
{
get
{
if(ProductID != 0)
{
...
return ImageSource.FromUri(link);
}
return null;
}
}
#endregion
public SharesViewModel(){}
public SharesViewModel(Share share)
{
ID = share.ID;
ProductID = share.ProductID;
JsonString = share.JsonString;
CreateDate = share.CreateDate;
LocationName = share.LocationName;
}
List View Model -- SharesListViewlModel
public class SharesListViewModel : BaseViewModel
{
private SharesViewModel _selectedShare;
private bool _isDataLoaded;
//grouped list
public ObservableCollection<LocationSpotGroups<string, SharesViewModel>> Shares { get; set; }
...
public ICommand OpenMoreSharesCommand { get; private set; }
public ICommand LoadDataCommand { get; private set; }
public SharesListViewModel(Position NW , Position SE)
{
_nw = NW;
_se = SE;
LoadDataCommand = new Command(async () => await LoadData());
OpenMoreSharesCommand = new Command<SharesViewModel>(async (share) => await OpenMoreShares(share));
public ObservableCollection<SharesViewModel> sList { get; set; }
= new ObservableCollection<SharesViewModel>();
}
private async Task LoadData()
{
if (_isDataLoaded)
return;
var list = await _connection.GetAllRegionShares(_nw, _se);
foreach (var spot in list)
{
sList.Add(new SharesViewModel(spot));
}
var sorted = from item in sList
orderby item.LocationName
group item by item.LocationName into itemGroup
select new LocationSpotGroups<string, SharesViewModel>(itemGroup.Key, itemGroup);
Shares = new ObservableCollection<LocationSpotGroups<string, SharesViewModel>>(sorted);
}
LocationSpotGroups
public class LocationSpotGroups<K, T> : ObservableCollection<T>
{
public K GroupKey { get; set; }
public IEnumerable<T> GroupedItem { get; set; }
public LocationSpotGroups(K key, IEnumerable<T> shares)
{
GroupKey = key;
GroupedItem = shares;
foreach (var item in shares)
{
this.Items.Add(item);
}
}
}
SharesPage XAML
<CollectionView x:Name="CollectionList"
VerticalOptions="FillAndExpand"
ItemsSource="{Binding Shares}"
IsGrouped="True">
<!--HEADER-->
<CollectionView.GroupHeaderTemplate>
<DataTemplate>
<StackLayout Orientation="Horizontal"
Padding="5"
BackgroundColor="#f7f7fb">
<Label x:Name="labelname"
Text="{Binding GroupKey}"
HorizontalOptions="Start"
VerticalOptions="Center"
TextColor="gray" />
</StackLayout>
</DataTemplate>
</CollectionView.GroupHeaderTemplate>
<CollectionView.ItemsLayout>
<GridItemsLayout Orientation="Vertical" Span="2" />
</CollectionView.ItemsLayout>
<!--BODY-->
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid Padding="5" Margin="8">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="50" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ImageButton Source="{Binding ImageLink}"
WidthRequest="150"
HeightRequest="150"
Grid.ColumnSpan="2"
CornerRadius="15"
Aspect="AspectFill"
Grid.Row="0"
Grid.Column="0"/>
<Label Text="{Binding ShoppingName}"
Grid.Row="1"
Grid.Column="0"/>
<Label Text="More"
Grid.Row="1"
Grid.Column="1"
HorizontalTextAlignment="End"/>
<Label Text="{Binding CreateDate}"
Grid.Row="2"
Grid.Column="0"/>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
SharesPage CS
public SharesPage( Position NW, Position SE )
{
InitializeComponent();
ViewModel = new SharesListViewModel(NW, SE);
}
public SharesListViewModel ViewModel
{
get { return BindingContext as SharesListViewModel; }
set { BindingContext = value; }
}
protected override void OnAppearing()
{
ViewModel.LoadDataCommand.Execute(null);
base.OnAppearing();
}
Loading the data in the constructor works if the data is not a lot, which is wasn't in my case. Everything loads perfectly.

I update ObservableCollection List but UI is not updating issue from Tab Page

I update ObservableCollection List but UI is not updating from Tab Page
I also clear List then Assign new list, Value of list is change but UI is not updated
public ObservableCollection<Dashboard> DetailsList { get; set; } = new ObservableCollection<Dashboard>();
//API Call
details = await _clientAPI.getDashboardDetails(id);
if (details != null)
{
DetailsList.Clear();
foreach (var item in details)
{
DetailsList.Add(item);
}
}
I think you miss to binding the context. Add the code below.
this.BindingContext = this;
I make a code sample for your reference. I am not sure what your Model, I use a simple model to test.
Page1.xaml.cs
public partial class Page1 : ContentPage
{
public ObservableCollection<Dashboard> DetailsList { get; set; }
public Page1()
{
InitializeComponent();
DetailsList = new ObservableCollection<Dashboard>()
{
new Dashboard(){ Name="AA", Country="CountryA"},
new Dashboard(){ Name="BB", Country="CountryB"},
};
this.BindingContext = this;
}
private void btnUpdate_Clicked(object sender, EventArgs e)
{
List<Dashboard> details = new List<Dashboard>();
details.Add(new Dashboard() { Name = "CC", Country = "CountryC" });
details.Add(new Dashboard() { Name = "DD", Country = "CountryD" });
if (details != null)
{
DetailsList.Clear();
foreach (var item in details)
{
DetailsList.Add(item);
}
}
}
}
public class Dashboard
{
public string Name { get; set; }
public string Country { get; set; }
}
Xaml:
<ContentPage.Content>
<StackLayout>
<Button
x:Name="btnUpdate"
Clicked="btnUpdate_Clicked"
Text="Update" />
<ListView ItemsSource="{Binding DetailsList}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<Label Text="{Binding Name}" />
<Label Text="{Binding Country}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
Updated:
public ObservableCollection<Dashboard> DetailsList { get; set; } = new ObservableCollection<Dashboard>();
//API Call
details = await _clientAPI.getDashboardDetails(id);
if (details != null)
{
DetailsList.Clear();
foreach (var item in details)
{
DetailsList.Add(item);
}
}
YourGridView.ItemSource =DetailsList;
YourGridView.ItemSource =DetailsList
You are missing this line. This code - it just assigns ObservableCollection to gridview (which you want to display the data)
Thanks!!!

WPF MVVM hierarchy selected item

I am currently implementing the application that displays hierarchy using ListBoxes (please do not suggest using TreeView, ListBoxes are needed).
It looks like that in the article: WPF’s CollectionViewSource (with source code).
Classes:
public class Mountains : ObservableCollection<Mountain>
{
public ObservableCollection<Lift> Lifts { get; }
public string Name { get; }
}
public class Lift
{
public ObservableCollection<string> Runs { get; }
}
The example uses CollectionViewSource instances (see XAML) to simplify the design.
An instance of Mountains class is the DataContext for the window.
The problem is: I would like that the Mountains class to have SelectedRun property and it should be set to currently selected run.
public class Mountains : ObservableCollection<Mountain>
{
public ObservableCollection<Lift> Lifts { get; }
public string Name { get; }
public string SelectedRun { get; set; }
}
Maybe I've missed something basic principle, but how can I achieve this?
You may want to read about the use of '/' in bindings. See the section 'current item pointers' on this MSDN article.
Here's my solution:
Xaml
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Margin="5" Grid.Row="0" Grid.Column="0" Text="Mountains"/>
<TextBlock Margin="5" Grid.Row="0" Grid.Column="1" Text="Lifts"/>
<TextBlock Margin="5" Grid.Row="0" Grid.Column="2" Text="Runs"/>
<ListBox Grid.Row="1" Grid.Column="0" Margin="5"
ItemsSource="{Binding Mountains}" DisplayMemberPath="Name"
IsSynchronizedWithCurrentItem="True" />
<ListBox Grid.Row="1" Grid.Column="1" Margin="5"
ItemsSource="{Binding Mountains/Lifts}" DisplayMemberPath="Name"
IsSynchronizedWithCurrentItem="True"/>
<ListBox Grid.Row="1" Grid.Column="2" Margin="5"
ItemsSource="{Binding Mountains/Lifts/Runs}"
IsSynchronizedWithCurrentItem="True"
SelectedItem="{Binding SelectedRun}"/>
</Grid>
C# (note, you don't need to implement INotifyPropertyChanged unless the properties will be changed and not just selected)
public class MountainsViewModel
{
public MountainsViewModel()
{
Mountains = new ObservableCollection<Mountain>
{
new Mountain
{
Name = "Whistler",
Lifts = new ObservableCollection<Lift>
{
new Lift
{
Name = "Big Red",
Runs = new ObservableCollection<string>
{
"Headwall",
"Fisheye",
"Jimmy's"
}
},
new Lift
{
Name = "Garbanzo",
Runs = new ObservableCollection<string>
{
"Headwall1",
"Fisheye1",
"Jimmy's1"
}
},
new Lift {Name = "Orange"},
}
},
new Mountain
{
Name = "Stevens",
Lifts = new ObservableCollection<Lift>
{
new Lift {Name = "One"},
new Lift {Name = "Two"},
new Lift {Name = "Three"},
}
},
new Mountain {Name = "Crystal"},
};
}
public string Name { get; set; }
private string _selectedRun;
public string SelectedRun
{
get { return _selectedRun; }
set
{
Debug.WriteLine(value);
_selectedRun = value;
}
}
public ObservableCollection<Mountain> Mountains { get; set; }
}
public class Mountain
{
public string Name { get; set; }
public ObservableCollection<Lift> Lifts { get; set; }
}
public class Lift
{
public string Name { get; set; }
public ObservableCollection<string> Runs { get; set; }
}
Here's how I would do it. You want to make sure that you fire the INotifyPropertyChanged event when setting the properties. To get the Selected Run you'll have to get MainViewModel.SelectedMountain.SelectedLift.SelectedRun.
public class MainViewModel: ViewModelBae
{
ObservableCollection<MountainViewModel> mountains
public ObservableCollection<MountainViewModel> Mountains
{
get { return mountains; }
set
{
if (mountains != value)
{
mountains = value;
RaisePropertyChanged("Mountains");
}
}
}
MountainViewModel selectedMountain
public MountainViewModel SelectedMountain
{
get { return selectedMountain; }
set
{
if (selectedMountain != value)
{
selectedMountain = value;
RaisePropertyChanged("SelectedMountain");
}
}
}
}
public class MountainViewModel: ViewModelBae
{
ObservableCollection<LiftViewModel> lifts
public ObservableCollection<LiftViewModel> Lifts
{
get { return lifts; }
set
{
if (lifts != value)
{
lifts = value;
RaisePropertyChanged("Lifts");
}
}
}
LiftViewModel selectedLift
public LiftViewModel SelectedLift
{
get { return selectedLift; }
set
{
if (selectedLift != value)
{
selectedLift = value;
RaisePropertyChanged("SelectedLift");
}
}
}
}
public class LiftViewModel: ViewModelBae
{
ObservableCollection<string> runs
public ObservableCollection<string> Runs
{
get { return runs; }
set
{
if (runs != value)
{
runs = value;
RaisePropertyChanged("Runs");
}
}
}
string selectedRun
public string SelectedRun
{
get { return selectedLift; }
set
{
if (selectedLift != value)
{
selectedLift = value;
RaisePropertyChanged("SelectedLift");
}
}
}
}
<ListBox ItemsSource="{Binding Mountains}" SelectedItem="{Binding SelectedMountain, Mode=TwoWay}">
<ListBox ItemsSource="{Binding SelectedMountain.Lifts}" SelectedItem="{Binding SelectedMountain.SelectedLift, Mode=TwoWay}">
<ListBox ItemsSource="{Binding SelectedMountain.SelectedLift.Runs}" SelectedItem="{Binding SelectedMountain.SelectedLift.SelectedRun, Mode=TwoWay}">
Your ViewModel should not also be a collection, it should contain collections and properties which are bound to the view. SelectedRun should be a property of this ViewModel (MountainViewModel) not Mountains. MountainViewModel should expose the Mountains collection and SelectedRun and should be bound to the listboxes' ItemsSource and SelectedItem.

Categories