In my Xamarin.Forms app, I have a ListView and am binding to the SelectedItem property:
<ListView x:Name="MyListView" ItemsSource="{Binding MyItems}" IsVisible="{Binding Expanded}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}" SelectionMode="Single" SeparatorVisibility="None">
<!-- not relevant code -->
</ListView>
When I run it on UWP, my SelectedItem property in my view model gets set when I select an item in the list. But not in ios. Am I doing something wrong? Or is there a work around?
I wrote a simple demo and it works on my side. Here is the code:
<ListView x:Name="testListView"
Style="{StaticResource ListStyle}" SelectedItem="{Binding YourSelectedItem, Mode=TwoWay}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Label Text="{Binding Name}"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Then in your view-model(viewModel should implement INotifyPropertyChanged):
class testViewModel : INotifyPropertyChanged
{
public string Name { get; set; }
private testViewModel _yourSelectedItem { get; set; }
public testViewModel YourSelectedItem
{
get
{
return _yourSelectedItem;
}
set
{
_yourSelectedItem = value;
OnPropertyChanged("YourSelectedItem");
}
}
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
And in the MainPage, set the BindingContext = new testViewModel();:
public partial class MainPage : ContentPage
{
ObservableCollection<testViewModel> myModels = new ObservableCollection<testViewModel>();
testViewModel model;
public MainPage()
{
InitializeComponent();
myModels.Add(new testViewModel { Name = "age" });
myModels.Add(new testViewModel { Name = "gender" });
myModels.Add(new testViewModel { Name = "name" });
testListView.ItemsSource = myModels;
BindingContext = new testViewModel();
}
}
Try it and let me know if it works for you.
Related
I have a Content page, which contain CollectionView inside CarouselView.
First time when the page is loading the double embedded binding is work fine. Show everithing correctly.
But when i try to change embedded property value nothing happen. How update these properties?
formChooseElement.formViewerElements[0].formViewerElementAnswares[0].color=Color.Green;
Like:
<CarouselView ItemsSource="{Binding formViewerElements}">
<CarouselView.ItemTemplate>
<DataTemplate>
<StackLayout>
<Label Text="{Binding text}" />
<CollectionView ItemsSource="{Binding formViewerElements}" >
<CollectionView.ItemTemplate>
<DataTemplate >
<StackLayout BackgroundColor="{Binding color}">
<Label Text="{Binding text}" >
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</StackLayout>
BindingContext in code behind:
this.BindingContext = new FormViewerViewModell();
ViewModell:
public class FormViewerViewModell : INotifyPropertyChanged
{
public FormViewerViewModell()
{
GenerateData
}
private FormChooseElement FormChooseElement;
public FormChooseElement formChooseElement
{
get => FormChooseElement;
set
{
FormChooseElement = value;
OnPropertyChanged(nameof(FormChooseElement));
}
}
public ObservableCollection<FormViewerElement> formViewerElements
{
get => formChooseElement.formViewerElements;
set
{ formChooseElement.formViewerElements = value;
OnPropertyChanged(nameof(formChooseElement.formViewerElements));
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
FormChooseElement
public class FormChooseElement
{
public ...
public ObservableCollection<FormViewerElement> formViewerElements { get; set; }
}
FormViewerElement
public class FormViewerElement
{
public ...
public ObservableCollection<FormViewerElementAnsware> formViewerElementAnswares { get; set; }
}
FormViewerElementAnsware
public class FormViewerElementAnsware
{
public ...
public Color color { get; set; };
Following this example to create a grouping for CollectionView, I notice that none of the properties are INotifyPropertyChanged, nor is the base class an ObservableCollection.
While the latter is easy to fix by changing List to ObservableCollection:
public class AnimalGroup : ObservableCollection<Animal>
{
public string Name { get; private set; }
public AnimalGroup(string name, ObservableCollection<Animal> animals) : base(animals)
{
Name = name;
}
private string _someOtherPropertyIWantToChangeAtRuntime = "hey";
public string SomeOtherPropertyIWantToChangeAtRuntime { get => _someOtherPropertyIWantToChangeAtRuntime, set => SetProperty(ref _someOtherPropertyIWantToChangeAtRuntime, value); }
}
It isn't clear how to make Name, or any other property (e.g. SomeOtherPropertyIWantToChangeAtRuntime), I want to associate with the group as an INotifyPropertyChanged. Treating it is as a normal class by adding the interface to base causes this warning:
Base interface 'INotifyPropertyChanged' is redundant because AnimalGroup inherits 'ObservableCollection'
Yet, there is nothing for the setter to call, such as SetProperty(ref _name, Value) and the existing PropertyChanged object is just for monitoring a group's collection changes. It isn't invokable, just handleable.
If I ignore the warning and implement INotifyPropertyChanged anyway (and name my event PropChanged to avoid colliding with ObservableCollection.PropertyChanged),
protected bool SetProperty<T>(ref T backingStore, T value, [CallerMemberName]string propertyName = "", Action onChanged = null)
{
if (EqualityComparer<T>.Default.Equals(backingStore, value))
return false;
backingStore = value;
onChanged?.Invoke();
PropChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
return true;
}
public event PropertyChangedEventHandler PropChanged;
and let my ViewModel manage the value of SomeOtherPropertyIWantToChangeAtRuntime, the bound <Label> never sees any changes.
<CollectionView ItemsSource="{Binding AnimalGroups}" HorizontalOptions="FillAndExpand">
<CollectionView.ItemsLayout>
<LinearItemsLayout Orientation="Vertical"/>
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout>
<StackLayout Orientation="Horizontal" HorizontalOptions="FillAndExpand">
<Label
Text="{Binding Name}"
HorizontalOptions="Start"
FontSize="24.44"
TextColor="Black"
FontAttributes="Bold"
Margin="0,0,0,10"/>
<Label
Text="{Binding SomeOtherPropertyIWantToChangeAtRuntime}" FontSize="15"
TextColor="Black"
Margin="0,0,0,0">
<Label.GestureRecognizers>
<TapGestureRecognizer Command="{Binding BindingContext.FindGroupAndChangeTextCommand, Source{x:Reference thisPageName}" CommandParameter="{Binding Name}"/>
</Label.GestureRecognizers>
</Label>
...
ViewModel:
public ObservableCollection<AnimalGroup> AnimalGroups {get; private set;}
public ICommand FindGroupAndChangeTextCommand {get; private set;}
public void FindGroupAndChangeText(string name)
{
var group = AnimalGroups.FirstOrDefault(t => t.Name == name);
if (group != null)
group.SomeOtherPropertyIWantToChangeAtRuntime = DateTime.Now.ToString();
}
ViewModel()
{
AnimalGroups = LoadData(); // not shown
FindGroupAndChangeTextCommand = new Command(FindGroupAndChangeText);
}
The result is that the label remains "hey" (which is the default value) and never changes even though I can see that the above command fires and the code finds the group and sets the text.
Agree with Jason, ObservableCollection has inherited INotifyPropertyChanged interface , So you will get the warning
Base interface 'INotifyPropertyChanged' is redundant because AnimalGroup inherits 'ObservableCollection'
And please see following screenshot about ObservableCollection<T>.
If you want to change the item at the runtime like this GIF.
Based on your code. I add two properties in the Animal class. For achieve the change the text of properties at the runtime, we can achieve the INotifyPropertyChanged in Animal class. Here is AnimalGroup.cs
public class AnimalGroup : ObservableCollection<Animal>
{
public string Name { get; private set; }
public AnimalGroup(string name, ObservableCollection<Animal> animals) : base(animals)
{
Name = name;
}
}
public class Animal : INotifyPropertyChanged
{
string animalName;
public string AnimalName
{
set
{
if (animalName != value)
{
animalName = value;
OnPropertyChanged("AnimalName");
}
}
get
{
return animalName;
}
}
string animalArea;
public string AnimalArea
{
set
{
if (animalArea != value)
{
animalArea = value;
OnPropertyChanged("AnimalArea");
}
}
get
{
return animalArea;
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
For testing click the command, I achieve the MyAnimalViewModel.cs like following code.
public class MyAnimalViewModel
{
public ObservableCollection<AnimalGroup> AnimalGroups { get; private set; } = new ObservableCollection<AnimalGroup>();
public ICommand FindGroupAndChangeTextCommand { protected set; get; }
public MyAnimalViewModel()
{
ObservableCollection<Animal> ts = new ObservableCollection<Animal>();
ts.Add(new Animal() { AnimalArea = "Asia", AnimalName = "cat" });
ts.Add(new Animal() { AnimalArea = "Asia", AnimalName = "dog" });
ObservableCollection<Animal> ts2 = new ObservableCollection<Animal>();
ts2.Add(new Animal() { AnimalArea = "Eourp", AnimalName = "keep" });
ts2.Add(new Animal() { AnimalArea = "Eourp", AnimalName = "gggg" });
AnimalGroups.Add(new AnimalGroup("Animal1", ts));
AnimalGroups.Add(new AnimalGroup("Animal2", ts2));
FindGroupAndChangeTextCommand = new Command<Animal>((key) =>
{
key.AnimalName = "testggggg";
});
}
}
I notice you want to achieve the group for CollectionView. Here is my edited layout.
<ContentPage.Content>
<CollectionView x:Name="MyCollectionView" ItemsSource="{Binding AnimalGroups}" IsGrouped="True" HorizontalOptions="FillAndExpand">
<CollectionView.ItemsLayout>
<LinearItemsLayout Orientation="Vertical"/>
</CollectionView.ItemsLayout>
<CollectionView.GroupHeaderTemplate>
<DataTemplate>
<Label Text="{Binding Name}"
BackgroundColor="LightGray"
FontSize="Large"
FontAttributes="Bold" >
</Label>
</DataTemplate>
</CollectionView.GroupHeaderTemplate>
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout>
<StackLayout Orientation="Horizontal" HorizontalOptions="FillAndExpand">
<Label
Text="{Binding AnimalArea}"
HorizontalOptions="Start"
FontSize="24.44"
TextColor="Black"
FontAttributes="Bold"
Margin="0,0,0,10"/>
<Label
Text="{Binding AnimalName}" FontSize="15"
TextColor="Black"
Margin="0,0,0,0">
<Label.GestureRecognizers>
<TapGestureRecognizer NumberOfTapsRequired="1"
Command="{ Binding BindingContext.FindGroupAndChangeTextCommand, Source={x:Reference Name=MyCollectionView} }" CommandParameter="{Binding .}"
/>
</Label.GestureRecognizers>
</Label>
</StackLayout>
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</ContentPage.Content>
Here is layout background code.
public partial class Page2 : ContentPage
{
public Page2()
{
InitializeComponent();
this.BindingContext = new MyAnimalViewModel();
}
}
I have a simple ContentPage with a StackLayout and a child ScrollView. As soon as I add an Items Template and DataTemplate to the page, all other content disappears, even content, such as a Label, that doesn't even use the data from the bound data source.
<ContentPage.Content>
<StackLayout>
<!-- Body -->
<ScrollView>
<StackLayout BindableLayout.ItemsSource="{Binding IdCardCollection }">
<BindableLayout.ItemTemplate>
<DataTemplate>
<!--<Label Text="{Binding IdCard.StateTerritoryCardTitle}" />-->
<Label Text="Test" />
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
</ScrollView>
</StackLayout>
</ContentPage.Content>
</ContentPage>
public partial class TestBinding : ContentPage
{
public TestBinding()
{
InitializeComponent();
BindingContext = new TestIdCardViewModel(1);
}
}
public class TestIdCardViewModel : BaseViewModel
{
private IList<IdCard> _idCards;
public ObservableCollection<IdCard> IdCardCollection { get; private set; }
public IdCard IdCard { get; private set; }
public TestIdCardViewModel()
{
}
public TestIdCardViewModel(int maxListItems) : base(maxListItems)
{
_idCards = new List<IdCard>();
CreateIdCardCollection(MaxListObjects);
}
private void CreateIdCardCollection(int maxListObjects)
{
_idCards.Add(new IdCard {StateTerritoryCardTitle = "Illinois - Proof of Auto Insurance" });
IdCardCollection = new ObservableCollection<IdCard>(_idCards);
IdCard = IdCardCollection.First();
}
}
public class BaseViewModel
{
public int MaxListObjects { get; set; } = (int) NGICConstants.MaxListItems;
public BaseViewModel()
{
}
public BaseViewModel(int maxListItems)
{
// Save the List count limit.
MaxListObjects = maxListItems;
}
}
No matter if I use the bound object or not, the Label does not appear. What am I doing wrong?
I have a collection view with the command binded, but for some reason when I select an item the action is never called in the viewmodel, heres my ViewModel code:
public class PlatillosViewModel : INotifyPropertyChanged
{
private INavigation Navigation;
public event PropertyChangedEventHandler PropertyChanged;
public List<PlatilloModel> Platillos { get; set; }
public List<GrupoModel> Grupos { get; set; }
public ICommand SelectedGroupCommand => new Command(SelectedGroup);
public PlatillosViewModel(INavigation navigation)
{
Navigation = navigation;
PlatillosRepository repository = new PlatillosRepository();
Platillos = repository.GetAll().ToList();
GrupoRepository grupoRepository = new GrupoRepository();
Grupos = grupoRepository.GetAll().ToList();
}
public ICommand SelectedPlatilloCommand => new Command<PlatilloModel>(async platillo =>
{
await Navigation.PushAsync(new PlatilloView());
});
void SelectedGroup()
{
PlatillosRepository platillosRepository = new PlatillosRepository();
//Platillos = platillosRepository.GetFilteredByGroup(grupoSeleccionado);
}
protected virtual void OnPropertyChanged(string property = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
}
}
And here is my Page:
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ComanderoMovil.Views.PlatillosView"
xmlns:ios="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core"
ios:Page.UseSafeArea="true"
xmlns:behaviorsPack="clr-namespace:Xamarin.Forms.BehaviorsPack;assembly=Xamarin.Forms.BehaviorsPack">
<ContentPage.Content>
<StackLayout>
<SearchBar> </SearchBar>
<StackLayout Orientation="Horizontal">
<CollectionView ItemsSource="{Binding Grupos}"
HeightRequest="50"
ItemsLayout="HorizontalList"
SelectionMode="Single"
SelectedItem="{Binding SelectedGroupCommand, Mode=TwoWay}">
<CollectionView.ItemTemplate>
<DataTemplate>
<ContentView>
<Label Margin="2"
BackgroundColor="Black"
Text="{Binding nombre}"
TextColor="White"
VerticalTextAlignment="Center"
HorizontalTextAlignment="Center"
FontSize="Small"></Label>
</ContentView>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</StackLayout>
<ListView Grid.Column="2"
HasUnevenRows="True"
SeparatorVisibility="None"
ItemsSource="{Binding Platillos}">
<ListView.Behaviors>
<behaviorsPack:SelectedItemBehavior Command="{Binding SelectedPlatilloCommand}"/>
</ListView.Behaviors>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ContentView Padding="2, 5, 5, 0">
<Frame OutlineColor="Black"
Padding="10"
HasShadow="False">
<StackLayout Orientation="Horizontal">
<Label Margin="10"
Text="{Binding clave_platillo}"
FontSize="Large"
HorizontalOptions="Start"></Label>
<Label Margin="10"
HorizontalTextAlignment="End"
Text="{Binding nombre}"></Label>
</StackLayout>
</Frame>
</ContentView>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
I have tried adding the command to the items inside the collection view, replacing labels for buttons, but still doesn't work, I've also tried to use SelectionChangedCommand in the collection view, and still the same issue, the only way I can make it work is handling the item selection in the View, but I want to stay true to MVVM.
Here is my GrupoModel:
public class GrupoModel
{
public string clave_grupo { get; set; }
public int id_clasificacion { get; set; }
public int id_grupo { get; set; }
public string nombre { get; set; }
public bool pedirClave { get; set; }
public bool status { get; set; }
public int tipo { get; set; }
}
and here is an image of what im trying to do:
If you read the document:
When the SelectionMode property is set to Single, a single item in the
CollectionView can be selected. When an item is selected, the
SelectedItem property will be set to the value of the selected item.
When this property changes, the SelectionChangedCommand is executed
(with the value of the SelectionChangedCommandParameter being passed
to the ICommand), and the SelectionChanged event fires.
When you want to bind a Commond, you should bind to the SelectionChangedCommand instead of SelectedItem. Change your code like below and it will work:
<CollectionView
HeightRequest="50"
ItemsLayout="HorizontalList"
SelectionMode="Single"
SelectionChangedCommand="{Binding SelectedGroupCommand, Mode=TwoWay}"
>
The command should go in the class of GrupoModel instead of the PlatillosViewModel
public List<GrupoModel> Grupos { get; set; }
Should be "linked" to class GrupoModel that have properties and a commandwhich will listen, something like:
Class GrupoModel
{
public int Id { get; set; }
public string Foo { get; set; }
public ICommand SelectedGroupCommand => new Command(Completar);
private async void Completar()
{
await ViewModels.PlatillosViewModel.GetInstancia().SelectedGroup(this);
}
}
This way each element of Grupos will have a command to listen.
BTW: Shouldn't Grupos be an ObservableCollection?
I try to bind an pivot to the DataContext in an Windows Universal app.
Everything works fine except it seems that I am unable to mix binding and "static" PivotItems.
I need to create 0 to n PivotItems based on a list and on static PivotItem containing settings.
This is what I tried. If I remove the HeaderTemplate and ItemTemplate Element the PivotItem-Element is shown. If I let the Template Elements on there place the bound data is shown but not the extra PivotItem.
Is it even possible to mix?
<Pivot Name="PivotMain" Title="Title" ItemsSource="{Binding Path=Parts}">
<Pivot.HeaderTemplate>
<DataTemplate x:DataType="viewmodel:DetailModel">
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</Pivot.HeaderTemplate>
<Pivot.ItemTemplate>
<DataTemplate x:DataType="viewmodel:DetailModel">
<TextBlock Text="TestTest"/>
</DataTemplate>
</Pivot.ItemTemplate>
<PivotItem Name="Settings" Header="Settings">
<ScrollViewer VerticalScrollMode="Auto" VerticalScrollBarVisibility="Auto">
<ListView ItemsSource="{Binding Path=Settings}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="viewmodel:SettingModel">
<RelativePanel>
<ToggleSwitch Name="OnOff"
OffContent="{Binding OffContent}" OnContent="{Binding OnContent}" IsOn="{Binding IsMonitored, Mode=TwoWay}"
RelativePanel.AlignLeftWithPanel="True" />
</RelativePanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ScrollViewer>
</PivotItem>
</Pivot>
Is it even possible to mix?
As far as I known, it is impossible. But you can use other ways to meet your requirements. What you actually want to do is the first one PivotItem has different content with others. You should be able use a DataTemplateSelector that you can select a different DataTemplate for the first item (which header is settings) with others. For example, code as follows:
XAML
<Page.Resources>
<DataTemplate x:Key="itemstemplate" x:DataType="local:DetailModel">
<TextBlock Text="TestTest"/>
</DataTemplate>
<DataTemplate x:Key="settingtemplate" x:DataType="local:DetailModel">
<ScrollViewer VerticalScrollMode="Auto" VerticalScrollBarVisibility="Auto">
<ListView ItemsSource="{Binding Path=Settingss}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="local:SettingModel">
<RelativePanel>
<ToggleSwitch Name="OnOff" OffContent="{Binding OffContent}" OnContent="{Binding OnContent}" IsOn="{Binding IsMonitored, Mode=TwoWay}" RelativePanel.AlignLeftWithPanel="True" />
</RelativePanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ScrollViewer>
</DataTemplate>
<local:PivotTemplateSelector
itemstemplate="{StaticResource itemstemplate}"
settingtemplate="{StaticResource settingtemplate}"
x:Key="PivotTemplateSelector" />
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Pivot Name="PivotMain" Title="Title" ItemsSource="{Binding Path=Parts}" ItemTemplateSelector="{StaticResource PivotTemplateSelector}">
<Pivot.HeaderTemplate>
<DataTemplate x:DataType="local:DetailModel">
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</Pivot.HeaderTemplate>
</Pivot>
</Grid>
Code behind
public sealed partial class MainPage : Page
{
ObservableCollection<DetailModel> Parts;
ObservableCollection<SettingModel> Settingss;
public MainPage()
{
this.InitializeComponent();
Settingss = new ObservableCollection<SettingModel>()
{
new SettingModel()
{
IsMonitored=true,
OffContent="work at",
OnContent="content"
}
};
Parts = new ObservableCollection<DetailModel>()
{
new DetailModel()
{
Name="Settings",
Settingss=Settingss
},
new DetailModel()
{
Name="test1"
},
new DetailModel()
{
Name="test2"
}
};
datasources datasource = new datasources()
{
Parts = Parts
};
this.DataContext = datasource;
}
}
public class PivotTemplateSelector : DataTemplateSelector
{
public DataTemplate itemstemplate { get; set; }
public DataTemplate settingtemplate { get; set; }
protected override DataTemplate SelectTemplateCore(object item)
{
DetailModel itemget = item as DetailModel;
if (itemget.Name == "Settings")
{
return settingtemplate;
}
else
return itemstemplate;
return base.SelectTemplateCore(item);
}
protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
{
return SelectTemplateCore(item);
}
}
public class datasources
{
public ObservableCollection<DetailModel> Parts { get; set; }
}
public class DetailModel
{
public string Name { get; set; }
public ObservableCollection<SettingModel> Settingss { get; set; }
}
public class SettingModel
{
public string OffContent { get; set; }
public string OnContent { get; set; }
public bool IsMonitored { get; set; }
}