Reputation: 621
In Xamarin Forms XAML, I want to hide part of ViewCell if it is not selected. For example the second label with text="Show only if selected". How to do that using MVVM without code behind?
<ListView x:Name="listView">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Label Text="Always Show it"/>
<Label Text="Show only if selected" IsVisible={Binding somewhere?}/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Upvotes: 0
Views: 3455
Reputation: 89285
Here is one possible MVVM approach, which involve no code-behind.
ViewModels
Add a property* in your ListView
item viewmodel to store information that indicate whether the item is currently selected :
public class ItemViewModel : INotifyPropertyChanged
{
......
private bool _isSelected;
public bool IsSelected
{
get { return _isSelected; }
set
{
if(_selectedItem != value)
{
_isSelected = value;
OnPropertyChanged();
}
}
}
}
Then in the page's viewmodel, have another property* for binding ListView
's SelectedItem
, in the setter of which you can setup IsSelected
value accordingly :
private ItemViewModel _selectedItem;
public ItemViewModel SelectedItem
{
get { return _selectedItem; }
set
{
if(_selectedItem != value)
{
//update previously selected item, if any :
if(_selectedItem != null) _selectedItem.IsSelected = false;
//update currently selected item :
value.IsSelected = true;
_selectedItem = value;
OnPropertyChanged();
}
}
}
View
Bind IsVisible
property to the ListView
item viewmodel :
<Label Text="Show only if selected" IsVisible="{Binding IsSelected}"/>
*) The property needs to be a public property, in a class that implements INotifyPropertyChanged
or inherits other class that implements it, and the property raises property-changed notification accordingly, as exemplified in the above snippets.
For reference:
Upvotes: 2
Reputation: 1858
Each item in your listview needs to have a "IsSelected" bindable property. Then on your listviews ItemSelected event get the item and set is IsSelected to true. Just make sure you keep a reference the the currently selected item so that you can set the IsSelected to false on it one a new selected item is pressed. It should look something like this.
MyItem _currentlySelectedItem;
void OnSelection (object sender, SelectedItemChangedEventArgs e)
{
if (e.SelectedItem == null) {
_currentlySelectedItem = null;
return; //ItemSelected is called on deselection, which results in SelectedItem being set to null
}
var selectedItem = e.SelectedItem as MyItem;
selectedItem .IsSelected= true;
_currentlySelectedItem.IsSelected= false; /// Make sure to check for null
_currentlySelectedItem = selectedItem ;
}
Upvotes: 0