Xamarin.Forms - Binding a command - c#

I am using ToolKits Expander and I am trying to bind a command, this is what I got so far:
public partial class AssignTaskPage : ContentPage
{
public AssignTaskPage()
{
InitializeComponent();
GetMathSubCatgories = new Command(() => MathSubCatgoriesCommand());
}
public ICommand GetMathSubCatgories { get; private set; }
void MathSubCatgoriesCommand()
{
Console.Write("Here");
}
}
And in my view
<xct:Expander Command="{Binding GetMathSubCatgories}">
<xct:Expander.Header>
<Frame Padding="10" Margin="10" HasShadow="False" BorderColor="LightGray" VerticalOptions="CenterAndExpand">
<StackLayout Orientation="Horizontal">
<Image Source="{Binding icon}" WidthRequest="25" HeightRequest="25"></Image>
<Label Text="{Binding name}" TextColor="{Binding textColor}" FontSize="Large" FontAttributes="Bold" HeightRequest="35" VerticalOptions="CenterAndExpand"></Label>
</StackLayout>
</Frame>
</xct:Expander.Header>
<Grid Padding="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ListView x:Name="SubCategories" ItemsSource="{Binding subCategories}" ItemSelected="SubCategories_ItemSelected">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Label Text="{Binding name}" TextColor="#02cc9d" FontAttributes="Bold" HeightRequest="35" VerticalOptions="CenterAndExpand"></Label>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</xct:Expander>
This does not work at all, (I put a break point on Console.Write("Here"); and its not hitting it)
So I did some digging and found this tutorial:
https://www.syncfusion.com/kb/12154/how-to-bind-command-to-expander-in-itemtemplate-of-xamarin-forms-listview-sflistview
and here is the sample in git.
https://github.com/SyncfusionExamples/command-to-expander-in-itemtemplate-listview-xamarin
I understand what I have to do here, the problem I am facing is when this Command is called, I was looking to get a value and use it in my AssignTaskPage, but what the tutorial is saying to have a ViewModel which is in a separate file. So should I setup a MessagingCenter in my AssignTaskPage and call it in the ViewModel to get the value I want and pass it to AssignTaskPage?

Because your command isn't defined in the ViewModel that you're binding to.You could bind the command which is defined in your AssignTaskPage,and then bind the viewmodel for the parent element of the expander.
For example :
public partial class AssignTaskPage : ContentPage
{
public AssignTaskPage()
{
InitializeComponent();
GetMathSubCatgories = new Command(() => MathSubCatgoriesCommand());
BindingContext = this;
}
public ICommand GetMathSubCatgories { get; private set; }
void MathSubCatgoriesCommand(object obj)
{
DisplayAlert("Alert!", "" + (obj as Contact).ContactName + "expanded", "Ok");
}
}
the xaml (here use the xaml codes of the above sample),the grid bind the viewmodel,and your expander bind the command of the root (your page):
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:ExpanderXamarin"
x:Class="ExpanderXamarin.ExpandableListView"
x:Name="root"
xmlns:sflistview="clr-namespace:Syncfusion.ListView.XForms;assembly=Syncfusion.SfListView.XForms"
xmlns:expander="clr-namespace:Syncfusion.XForms.Expander;assembly=Syncfusion.Expander.XForms">
<ContentPage.Content>
<Grid x:Name="mainGrid" BackgroundColor="#F0F0F0" Padding="4">
<Grid.BindingContext>
<local:ViewModel />
</Grid.BindingContext>
<sflistview:SfListView x:Name="listView" AutoFitMode="DynamicHeight" ItemsSource="{Binding ContactsInfo}">
<sflistview:SfListView.ItemTemplate>
<DataTemplate>
<Frame x:Name="frame" CornerRadius="2" Padding="{OnPlatform Android=1, iOS=1, UWP=0}" Margin="{OnPlatform Android=1, iOS=1, UWP=0}" OutlineColor="White" HasShadow="{OnPlatform Android=true, iOS=false, UWP=true}">
<Grid Padding="{OnPlatform Android=2, iOS=2, UWP=0}" Margin="{OnPlatform Android=1, iOS=1, UWP=0}" BackgroundColor="White" >
<expander:SfExpander x:Name="expander" HeaderIconPosition="None">
<expander:SfExpander.Behaviors>
<local:EventToCommandBehavior Command="{Binding Path=BindingContext.GetMathSubCatgories, Source={x:Reference root}}" EventName="Expanding" CommandParameter="{Binding .}"/>
</expander:SfExpander.Behaviors>
<expander:SfExpander.Header>
...
</expander:SfExpander.Header>
<expander:SfExpander.Content>
..
</expander:SfExpander.Content>
</expander:SfExpander>
</Grid>
</Frame>
</DataTemplate>
</sflistview:SfListView.ItemTemplate>
</sflistview:SfListView>
</Grid>
</ContentPage.Content>
</ContentPage>
if you want get the parameters you could bind the CommandParameter like above.

Related

How To bind Listview with variable in content page

I would like to bind my list view with string variable and image in my classe.
Here is my Xalm code :
<ListView x:Name="ListViewWordDescriptionOnline"
HasUnevenRows="True"
VerticalOptions="Fill">
<ListView.ItemTemplate >
<DataTemplate>
<ViewCell IsEnabled="False" >
<ViewCell.View>
<Label Text="{Binding .}" TextColor="#7D7D7D" FontSize="14" Grid.Column="0"/>
<Label Text="BIND WITH VARIABLE BingStringValue IN PUBLIC CLASS" />
<Image Source=" BIND WITH IMAGE BingImageValue IN PUBLIC CLASS" />
</Grid>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Here is my C# code :
public partial class MainPage : ContentPage
{
public MainPage()
{
List<string> animals= new List<string> { "bird", "dog" };
ListViewWordDescriptionOnline.ItemsSource=animals;
string BingStringValue ="This is type 1"
var BingImageValue= ImageSource.FromResource("MyImages.WordsPage.AddWords.png");
}
}
Thanks for your help
You alse could define a Name to the root contentpage,then use Binding Path to bind the BingStringValue and BingImageValue.
the page.xaml.cs:
public partial class MainPage : ContentPage
{
public string BingStringValue { get; set; }
public ImageSource BingImageValue { get; set; }
public MainPage()
{
InitializeComponent();
List<string> animals = new List<string> { "bird", "dog" };
ListViewWordDescriptionOnline.ItemsSource = animals;
BingStringValue = "This is type 1";
BingImageValue = ImageSource.FromResource("NewerForms.fivePlus.png");
BindingContext = this;
}
}
then in the xaml:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="NewerForms.Page3"
x:Name="root"
>
<ContentPage.Content>
<StackLayout>
<ListView x:Name="ListViewWordDescriptionOnline" HasUnevenRows="True" VerticalOptions="Fill">
<ListView.ItemTemplate >
<DataTemplate>
<ViewCell>
<ViewCell.View>
<Grid>
<Label Text="{Binding .}" TextColor="#7D7D7D" FontSize="14" Grid.Column="0"/>
<Label Text="{Binding Source={x:Reference root},
Path=BingStringValue}" />
<Image Source="{Binding Source={x:Reference root},
Path=BingImageValue}" />
</Grid>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
</ContentPage>

Behaviors.Forms Command not Executing

I am attempting to upgrade an existing Xamarin project to the latest versions of various libraries. The Xamarin forms themselves live in a shared library. My page has a ListView on it & I am attempting to capture the event fired when an item is 'chosen'. However, the ICommand in my ViewModel is not executing.
NOTES:
I am using Xamarin.Forms 4.8...but had to downgrade Behaviors.Forms to 1.3 because the code is in a .NET Standard library.
If I upgrade to Behaviors.Forms 1.4 a design-time error occurs (see photo below)
SHARED LIBRARY INFORMATION:
.NET Standard 2.0
Acr.UserDialogs Version="7.1.0.454"
AzureMobileClient.Helpers Version="4.0.2.507-pre"
Behaviors.Forms Version="1.3.0"
Com.Airbnb.Xamarin.Forms.Lottie Version="3.1.3"
Prism.DryIoc.Forms Version="8.0.0.1850-pre"
Prism.Forms Version="8.0.0.1850-pre"
Refractored.MvvmHelpers Version="1.6.2"
Telerik.UI.for.Xamarin.Common Version="2020.2.624.1"
Telerik.UI.for.Xamarin.DataControls Version="2020.2.624.1"
Telerik.UI.for.Xamarin.DataGrid Version="2020.2.624.1"
Telerik.UI.for.Xamarin.Primitives Version="2020.2.624.1"
Telerik.UI.for.Xamarin.SkiaSharp Version="2020.2.624.1"
Xamarin.FFImageLoading.Forms Version="2.4.11.982"
Xamarin.FFImageLoading.Svg.Forms Version="2.4.11.982"
Xamarin.FFImageLoading.Transformations Version="2.4.11.982"
Xamarin.Forms Version="4.8.0.1364"
CONVERTER CLASS:
The original programmer returns 'ItemTapped' EventArgs...
public class SelectedItemEventArgsConverter : IValueConverter
{
#region <Methods>
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var eventArgs = value as ItemTappedEventArgs;
return eventArgs != null ? eventArgs.Item : null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
VIEW MODEL:
The ListView binds-up & displays items (see photo's below)...
using CustomControls;
using Models;
using MvvmHelpers.Commands;
using Prism.Navigation;
using Prism.Services;
using System.Collections.Generic;
public class MainPageViewModel : ViewModelBase
{
#region Constructors
public MainPageViewModel(INavigationService navigationService, IPageDialogService pageDialogService, IDeviceService deviceService) : base(navigationService, pageDialogService, deviceService)
{
Initialize();
}
#endregion
#region <Properties>
public AccordionNode ShakeoutListItemsAccordion { get; private set; }
public Command<SimpleListItem> OnShakeoutListItemSelectedCommand { get; private set; }
public List<SimpleListItem> ShakeoutListItems { get; private set; } = new List<SimpleListItem>();
#endregion
#region <Events>
public async void OnShakeoutListItemSelected(SimpleListItem item)
{
if (item.Name == "Add Shakeout")
await NavigationService.NavigateAsync("ShakeoutDocumentGeneratorPage");
}
#endregion
private void Initialize()
{
// Commands
OnShakeoutListItemSelectedCommand = new Command<SimpleListItem>(OnShakeoutListItemSelected);
// Accordians
ShakeoutListItemsAccordion = new AccordionNode("OverwrittenInView", GlobalVariables.Accordion.Height, GlobalVariables.Accordion.HeaderBackgroundColor, GlobalVariables.Accordion.HeaderColorTextColor, GlobalVariables.Accordion.SeparatorColor);
// Data
ShakeoutListItems.Add(new SimpleListItem { Name = "Add Shakeout", Title = string.Empty, Type = string.Empty });
}
}
VIEW:
Because the converter-class 'ItemTapped' EventArgs, I am focusing-on that event...but I can chane this (if needed)
<?xml version="1.0" encoding="utf-8" ?>
<views:BaseContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:behaviors="clr-namespace:Behaviors;assembly=Behaviors"
xmlns:forms="clr-namespace:FFImageLoading.Svg.Forms;assembly=FFImageLoading.Svg.Forms"
xmlns:converters="clr-namespace:ETC.Operations.Pulse.Mobile.Converters;assembly=ETC.Operations.Pulse.Mobile"
xmlns:customControls="clr-namespace:ETC.Operations.Pulse.Mobile.CustomControls;assembly=ETC.Operations.Pulse.Mobile"
xmlns:helpers="clr-namespace:ETC.Operations.Pulse.Mobile.Helpers;assembly=ETC.Operations.Pulse.Mobile"
xmlns:views="clr-namespace:ETC.Operations.Pulse.Mobile.Views;assembly=ETC.Operations.Pulse.Mobile"
x:Class="ETC.Operations.Pulse.Mobile.MainPage">
<ContentPage.Resources>
<ResourceDictionary>
<converters:SelectedItemEventArgsConverter x:Key="EventToCommand"/>
<forms:SvgImageSourceConverter x:Key="SvgImageSourceConverter"></forms:SvgImageSourceConverter>
</ResourceDictionary>
</ContentPage.Resources>
<ContentPage.Content>
<ScrollView VerticalOptions="FillAndExpand" Padding="10">
<StackLayout Spacing="0" Padding="0">
<!-- SHAKEOUTS -->
<StackLayout Spacing="0" Padding="0" Style="{DynamicResource AccordionTitleStyle}">
<StackLayout Style="{DynamicResource AccordionHeaderStackLayoutStyle}">
<StackLayout.GestureRecognizers>
<TapGestureRecognizer Command="{Binding ShakeoutListItemsAccordion.ExpandContractAccordion}"/>
</StackLayout.GestureRecognizers>
<Label Text="Shakeouts" Style="{DynamicResource AccordionHeaderTextStyle}" VerticalTextAlignment="Center"/>
<Label TextColor="{Binding ShakeoutListItemsAccordion.HeaderTextColor}" HorizontalOptions="EndAndExpand" Text="{Binding ShakeoutListItemsAccordion.IconText}" VerticalTextAlignment="Center"/>
</StackLayout>
<BoxView HeightRequest="1" Color="{Binding ShakeoutListItemsAccordion.LineColor}" HorizontalOptions="FillAndExpand"></BoxView>
</StackLayout>
<!-- SHAKEOUTS: Controls -->
<StackLayout BackgroundColor="{DynamicResource BackgroundColor}" HeightRequest="200" IsVisible="{Binding ShakeoutListItemsAccordion.IsExpanded}" Padding="0" Spacing="0">
<ListView
x:Name="lvShakeoutListItems"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand"
ItemsSource="{Binding ShakeoutListItems}"
RowHeight="40">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid Style="{DynamicResource ListViewGridItemStyle}" RowSpacing="0" ColumnSpacing="0" Margin="13,0,0,0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.8*" />
<ColumnDefinition Width="150" />
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Text="{Binding Name}" Style="{DynamicResource ListViewLabelCenterRowLeft}" TextColor="{StaticResource LabelValueTextColor}" Margin="0,10,0,0"/>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.Behaviors>
<behaviors:EventHandlerBehavior EventName="ItemTapped">
<behaviors:InvokeCommandAction Command="{Binding OnShakeoutListItemSelectedCommand}" Converter="{StaticResource EventToCommand}" />
</behaviors:EventHandlerBehavior>
</ListView.Behaviors>
</ListView>
</StackLayout>
</StackLayout>
</ScrollView>
</ContentPage.Content>
</views:BaseContentPage>
PHONE IMAGES:
As you can see...the ViewModel is binding to data.
NOTES:
Upgrading to Behaviors.Forms 1.4 generates a design-time error.
UPDATES:
Here are my updates on the suggestions being made by contributors...
The 'Tap gesture on main cell object' option does not fire an event (at all)
The 'selected Item' event raises...but does not call the "MainPageViewModel OnShakeoutListItemSelected" event
I am currently looking at "Corcav Behavior" in NuGet
Option 1 : Use tap gesture on main cell object
<ListView
x:Name="lvShakeoutListItems"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand"
ItemsSource="{Binding ShakeoutListItems}"
RowHeight="40">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid Style="{DynamicResource ListViewGridItemStyle}" RowSpacing="0" ColumnSpacing="0" Margin="13,0,0,0">
**<Grid.GestureRecognizers>
<TapGestureRecognizer Command="{Binding OnShakeoutListItemSelectedCommand}" CommandParameter="{Binding .}"/>
</Grid.GestureRecognizers>**
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.8*" />
<ColumnDefinition Width="150" />
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Text="{Binding Name}" Style="{DynamicResource ListViewLabelCenterRowLeft}" TextColor="{StaticResource LabelValueTextColor}" Margin="0,10,0,0"/>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Option 2: Use selected Item on main cell object
<ListView
x:Name="lvShakeoutListItems"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand"
ItemsSource="{Binding ShakeoutListItems}"
SelectedItem="{Binding SelctedItem}"
RowHeight="40">
...
</>
Option 3 : Use corcav behavior nuget to get event to command behavior

BindingContext with command and parameter binding

I have a ViewModel, from which i construct a collection of objects. I want to be able to bind my objects on my view, while at the same time being able to use my button.
Currently, my properties are correctly bound to my labels (partnerLogo, partnerText, partnerLink). Unfortunately I'm not able to use my button command to send the command parameter that I bind.
ViewModel
Public class CarouselViewModel : INotifyPropertyChanged
{
public CarouselViewModel()
{
partners = new ObservableCollection<Carousel>()
{
new Carousel(){partnerText = "Test123", partnerLogo = "Test123", partnerLink = "Test123" },
};
openWebsite = new Command<string>((key) =>
{
Device.OpenUri(new Uri(key));
});
}
public ObservableCollection<Carousel> partners
{
get;
set;
}
public ICommand openWebsite
{
private set;
get;
}
}
XAML:
<CarouselView ItemsSource="{Binding partners}">
<CarouselView.ItemsLayout>
<GridItemsLayout/>
</CarouselView.ItemsLayout>
<CarouselView.ItemTemplate>
<DataTemplate>
<Frame>
<StackLayout>
<Image Source="{Binding partnerLogo}"/>
<Label Text="{Binding partnerText}"/>
<Button Text="Read" Command="{Binding openWebsite}" CommandParameter="{Binding partnerLink}"/>
</StackLayout>
</Frame>
</DataTemplate>
</CarouselView.ItemTemplate>
</CarouselView>
How do I access my button command, while at the same time being able to send the commandparameter?
For each item in the CarouselView, the binding context will be underlying data item which is bound to ItemsSource i.e., Carousel. And for CarouselView, the binding context will be your ViewModel class if you have defined it.
To resolve the issue, set the x:Name="mycaroselview" to CarouselView in the XAML and refer it's path reference to the Button command as like below code example.
<CarouselView x:Name="MyCarousel" ItemsSource="{Binding partners}">
<CarouselView.ItemsLayout>
<GridItemsLayout/>
</CarouselView.ItemsLayout>
<CarouselView.ItemTemplate>
<DataTemplate>
<Frame>
<StackLayout>
<Image Source="{Binding partnerLogo}"/>
<Label Text="{Binding partnerText}"/>
<Button Text="Read" Command="{Binding BindingContext.openWebsite, Source={x:Reference Name=MyCarousel}}" CommandParameter="{Binding partnerLink}"/>
</StackLayout>
</Frame>
</DataTemplate>
</CarouselView.ItemTemplate>
Make sure that you must set the binding context either to ContentPage or CarouselView.
Regards,
Dinesh
What you can do is, give a x:name to the content Page that you are using:-
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MyProject;assembly= MyProject"
x:Class="MyProject.Views.MyPage"
x:Name="ThisPage">
And then give Source to the Command. Like this. This method will call the Command that is there in the ViewModel of the Current Page. Also, you can use a Command Parameter to know which Item has Triggered the Command.
<CarouselView ItemsSource="{Binding partners}">
<CarouselView.ItemsLayout>
<GridItemsLayout/>
</CarouselView.ItemsLayout>
<CarouselView.ItemTemplate>
<DataTemplate>
<Frame>
<StackLayout>
<Image Source="{Binding partnerLogo}"/>
<Label Text="{Binding partnerText}"/>
<Button Text="Read" Command="{Binding openWebsite, Source={x:Reference Name=ThisPage}}" CommandParameter="{Binding partnerLink}"/>
</StackLayout>
</Frame>
</DataTemplate>
</CarouselView.ItemTemplate>
</CarouselView>

Xamarin Forms Command Binding inside ListView is not working

i'm trying to bind a command to a button inside a listView, but without success. I follow all other answers posted here, like this one:
Xamarin Forms Button Command binding inside a ListView
The actual result is that nothing happens. A thing that i notice is that visual studio, when i type after x:Reference suggests me just GridWebcam, like if it doesn't see other reference elements. What can i do?
Here my code:
<ContentPage
...
x:Name="WebcamList">
<ContentPage.Resources>
...
<ContentPage.Content>
<ListView ItemsSource="{Binding ListOfWebcam}"
SeparatorVisibility="None"
CachingStrategy="RecycleElement"
RowHeight="250"
VerticalOptions="FillAndExpand"
x:Name="ListWebcam">
<ListView.Header>
<StackLayout x:Name="HeaderStackLayout"
Padding="5,25,0,30"
Orientation="Horizontal"
HorizontalOptions="FillAndExpand">
<Label x:Name="LabelHeader"
Text="Webcam:"
FontSize="Large"
FontAttributes="Bold"
TextColor="{x:Static statics:Palette.PrimaryColor}"
VerticalOptions="Center"
HorizontalOptions="Start" Margin="10,0,0,0"/>
</StackLayout>
</ListView.Header>
<ListView.ItemTemplate>
<DataTemplate>
<controls:ExtendedViewCell IsEnabled="False">
<controls:ExtendedViewCell.View>
<Grid x:Name="GridWebcam">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Frame Grid.Column="1"
Grid.RowSpan="2"
CornerRadius="20"
BackgroundColor="{x:Static statics:Palette.PrimaryColor}"
VerticalOptions="FillAndExpand"
HorizontalOptions="FillAndExpand"
HasShadow="True"
Margin="5,10">
<StackLayout>
<Label Text="{Binding t_str_vid,Converter={StaticResource WebcamNameConverter}}"
FontSize="Medium"
TextColor="White"
FontAttributes="Bold"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand">
</Label>
<Label TextColor="White"
FontSize="Medium"
Text="{Binding direzione,Converter={StaticResource DirectionToStringConverter}}"/>
<StackLayout Orientation="Horizontal">
<ffimageloading:CachedImage LoadingPlaceholder="Rolling.gif"
DownsampleToViewSize="False"
VerticalOptions="FillAndExpand"
HorizontalOptions="StartAndExpand"
Source="{Binding image1}"/>
<iconize:IconButton Text="fas-play-circle"
FontSize="50"
HorizontalOptions="EndAndExpand"
VerticalOptions="EndAndExpand"
TextColor="White"
Command="{Binding BindingContext.OpenVideoWebcamCommand, Source={x:Reference WebcamList}}"
CommandParameter="{Binding .}"
BackgroundColor="Transparent"/>
</StackLayout>
</StackLayout>
</Frame>
</Grid>
</controls:ExtendedViewCell.View>
</controls:ExtendedViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage.Content>
</ContentPage>
```
public class WebcamListViewModel : BaseViewModel
{
public ICommand OpenVideoWebcamCommand { set; get; }
private List<Webcam> _ListOfWebcam { get; set; }
public List<Webcam> ListOfWebcam
{
get { return _ListOfWebcam; }
set
{
_ListOfWebcam = value;
OnPropertyChanged();
}
}
private Task DownloadFramesTask;
CancellationTokenSource tokenSourceDownloadFrames = new CancellationTokenSource();
CancellationToken cancellationTokenDownloadFrames;
public WebcamListViewModel(INavigationService navigationService, IApiAutostradeManagerFactory apiAutostradeManagerFactory) : base(navigationService,apiAutostradeManagerFactory)
{
OpenVideoWebcamCommand = new Command<Webcam>(async (webcam) => {
await navigationService.NavigateAsync(Locator.WebcamVideoPopUpPage);
Messenger.Default.Send(new InfoWebcamVideoMessage(webcam.c_mpr, webcam.c_uuid, webcam.t_str_vid));
});
}
Well it could be related to this mysterious controls:ExtendedViewCell of yours :)
Also did you disable the ListView selection: <ListView ... SelectionMode="None" /> ?
As Roubachof said that I don't know if it is related to controls:ExtendedViewCell,please check if you have binding BindingContext, then you can take a look the following code:
<StackLayout>
<ListView x:Name="listview1" ItemsSource="{Binding persons}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<Label Text="{Binding Id}" />
<Label Text="{Binding name}" />
<Button
Command="{Binding BindingContext.command, Source={x:Reference listview1}}"
CommandParameter="{Binding Id}"
Text="Delete item" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
public partial class Page1 : ContentPage
{
public ObservableCollection<person> persons { get; set; }
public RelayCommand1 command { get; set; }
public Page1 ()
{
InitializeComponent ();
persons = new ObservableCollection<person>();
for(int i =0;i<20;i++)
{
person p = new person()
{
Id = i,
name = "cherry" + i
};
persons.Add(p);
command = new RelayCommand1(obj => method1((int)obj));
}
this.BindingContext = this;
}
public void method1(int Id)
{
persons.RemoveAt(Id);
//IEnumerable<person> list = persons.Where(x => x.Id == Id);
//foreach (person m in list)
//{
//}
}
}
public class person
{
public int Id { get; set; }
public string name { get; set; }
}

not able to toggle Switch

At the moment I am programming an application based on Xamarin. My goal is to toggle the switch based on values in a table. Problem is, Xamarin is not noticing my x:Name toggle_true connected to my switch.
Here is my script in xaml:
<ListView x:Name="defineBuildingItems">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<StackLayout Orientation="Vertical">
<Label Text="{Binding defineDescription}" x:Name="Current_item"/>
</StackLayout>
<Switch BindingContext ="{Binding defineId}" HorizontalOptions="EndAndExpand"
Toggled="Handle_Toggled" x:Name="toggled_true"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Here is my c# code in code behind:
var currentQuestions = _define.Where(s => DefineId.Contains(s.defineId));
//Remember what building was defined like last time defineBuilding was proceeded.
foreach (DefineTable i in currentQuestions)
{
toggled_true.IsToggled = true;
}
defineBuildingItems.ItemsSource = posts;
base.OnAppearing();
}
Notice how it recognizes the x:Name defineBuildingItems. The error i get on toggled_true is: The name toggled_true does not exist in the current namespace. Is there something I am doing wrong or missing?
Access to control by name inside datatemplate not working. You must using binding. This is simply example:
Model:
public class Data
{
public bool IsToggled {get;set;}
....
}
Code behind:
public YourPage
{
BindingContext = this;
}
....
private List<Data> _items;
public List<Data> Items
{
get { return _items;}
set
{
_items = value;
OnPropertyChanged();
}
}
Your xaml:
<ListView x:Name="defineBuildingItems" ItemSources={Binding Items}>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<StackLayout Orientation="Vertical">
<Label Text="{Binding defineDescription}" />
</StackLayout>
<Switch IsToggled ="{Binding IsToggled, Mode =TwoWay}" HorizontalOptions="EndAndExpand" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

Categories

Resources