I have a CollectionView which has 1 Frame inside, and the backgroundcolor of the Frame would change bases on the string value of the variable "GetColor" that collects string data from each object of Database, but the backgroundcolor of the Frame remains as "Red" all the time.
#CollectionView
<CollectionView Margin="5" ItemsSource="{Binding ListGroupData}"
ItemsUpdatingScrollMode="KeepLastItemInView" ItemTemplate="{StaticResource
GroupDataTemplateSelector}" VerticalOptions="FillAndExpand"
HorizontalOptions="FillAndExpand"/>
<ResourceDictionary>
<DataTemplate x:Key="RedTemplate">
<StackLayout>
<Frame HasShadow="False" Padding="10" HorizontalOptions="StartAndExpand"
BackgroundColor="Red"
CornerRadius="15">
<Label Text="{Binding Name}" TextColor="Black"/>
</Frame>
</StackLayout>
</DataTemplate>
<DataTemplate x:Key="GreenTemplate">
<StackLayout>
<Frame HasShadow="False" Padding="10" HorizontalOptions="EndAndExpand"
BackgroundColor="Green"
CornerRadius="15">
<Label Text="{Binding Name}" TextColor="Black"/>
</Frame>
</StackLayout>
</DataTemplate>
<Local:GroupDataViewModel x:Key="GroupDataTemplateSelector" RedTemplate="
{StaticResource
RedTemplate}" GreenTemplate="{StaticResource GreenTemplate}"/>
</ResourceDictionary>
#TemplateSelector Code
protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
{
if (GetColor == "Red")
return RedTemplate;
else
return GreenTemplate;
}
public DataTemplate RedTemplate { get; set; }
public DataTemplate GreenTemplate { get; set; }
#Public Variable
public string GetColor;
public ObservableCollection<GroupData> ListGroupData = new ObservableCollection<GroupData>();
#Supported Code
FirebaseClient fc = new FirebaseClient("...");
var result = await fc.Child("GroupData").OnceAsync<GroupData>();
foreach (var item in result)
{
GetColor = item.Object.Color;
ListGroupData.Add(item.Object);
}
///this part the item that is being added to the ListGroupData(CollectionView) suppose to
have different backgroundcolor bases on its data
You dont need the public property GetColor. Because that property gets evaluated for every object in the collection, not in the viewmodel.
You will need to modify your Template selector
protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
{
//Your list is a list of GroupData. then you will need to cast item to the type of your object
var targetColor = (GroupData)item.Color;
if (targetColor == "Red") //this if the item.Color is String
return RedTemplate;
else
return GreenTemplate;
}
PD:
Or if your item.Color is a Color type, you can just use it inside the CollectionView.ItemTemplate to colour your Frame.You just have to add a binding to that property. (and you can delete all the TemplateSelector code)
If your item.Color is not a Color type, you will have to add a Converter (you will have to code it), to transform the value into a Color.
<CollectionView Margin="5"
ItemsSource="{Binding ListGroupData}"
ItemsUpdatingScrollMode="KeepLastItemInView"
VerticalOptions="FillAndExpand"
HorizontalOptions="FillAndExpand">
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout>
<Frame HasShadow="False"
Padding="10"
HorizontalOptions="EndAndExpand"
BackgroundColor="{Binding Color}"
CornerRadius="15">
<Label Text="{Binding Name}" TextColor="Black"/>
</Frame>
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
Related
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.
I have a CollectionView with a few items in it. I'm trying to adjust the size of the CollectionView to be just big enough to fit all of its children. Right now, it's much larger than the amount of children it has.
The Blue color represents the size of the CollectionView. As you can see, it's well beyond the size of it's children. I'd like it to fit them perfectly, or at the very least be closer to the same size.
I don't have any height requests on any of the elements on the page, including the CollectionView.
Here's my code. It's not particularly pretty at the moment, but it's a work in progress.
<StackLayout>
<CollectionView x:Name="assessmentsCollectionView"
BackgroundColor="Blue">
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout Spacing="10"
Padding="5">
<Frame CornerRadius="5"
Padding="0"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand">
<StackLayout Orientation="Horizontal">
<Frame Padding="5"
CornerRadius="0"
WidthRequest="50">
<Label Text="{Binding TypeLetter}"
TextColor="#37474f"
FontSize="24"
VerticalTextAlignment="Center"
HorizontalTextAlignment="Center"/>
</Frame>
<StackLayout Padding="10">
<Label Text="{Binding Name}"
TextColor="Black"
FontSize="24"/>
<StackLayout Orientation="Horizontal">
<Image Source="calendarIcon.png"
WidthRequest="12"
HeightRequest="12"/>
<Label Text="{Binding Date}"
FontSize="12"
TextColor="Gray"/>
</StackLayout>
</StackLayout>
</StackLayout>
</Frame>
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</StackLayout>
I changed CollectionView to FlexLayout with BindableLayout.ItemsSource and BindableLayout.ItemTemplate
What was previously
<CollectionView.ItemTemplate>
<DataTemplate>
...
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
What was done
<FlexLayout Direction="Column"
x:Name="MessagesList"
AutomationId="MessagesList"
BindableLayout.ItemsSource="{Binding Messages}" >
<BindableLayout.ItemTemplate>
<DataTemplate>
...
</DataTemplate>
</BindableLayout.ItemTemplate>
</FlexLayout>
For me works well, no need to set Height for item or FlexLayout, all are dynamic
If you have little rows in Collectionview, you can set a value to collectionView.HeightRequest. when item increase, the height will increase as well.
I create a property called.RowHeigth. If I add item in the CollectionView(with AddCommand), RowHeigth will increase.
<StackLayout>
<CollectionView
x:Name="assessmentsCollectionView"
BackgroundColor="Blue"
HeightRequest="{Binding rowHeigth}"
ItemsSource="{Binding letters}">
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout Padding="5" Spacing="10">
<Frame
Padding="0"
CornerRadius="5"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand">
<StackLayout Orientation="Horizontal">
<Frame
Padding="5"
CornerRadius="0"
WidthRequest="50">
<Label
FontSize="24"
HorizontalTextAlignment="Center"
Text="{Binding TypeLetter}"
TextColor="#37474f"
VerticalTextAlignment="Center" />
</Frame>
<StackLayout Padding="10">
<Label
FontSize="24"
Text="{Binding Name}"
TextColor="Black" />
<StackLayout Orientation="Horizontal">
<Image
HeightRequest="12"
Source="c1.png"
WidthRequest="12" />
<Label
FontSize="12"
Text="{Binding Date}"
TextColor="Gray" />
</StackLayout>
</StackLayout>
</StackLayout>
</Frame>
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
<Button
x:Name="btn1"
Command="{Binding AddCommand}"
Text="btn1" />
</StackLayout>
public partial class Page4 : ContentPage
{
public Page4()
{
InitializeComponent();
this.BindingContext = new letterviewmodel(); ;
}
}
public class letterviewmodel: INotifyPropertyChanged
{
public ObservableCollection<lettermodel> letters { get; set; }
private int _rowHeigth;
public int rowHeigth
{
get { return _rowHeigth; }
set
{
_rowHeigth = value;
RaisePropertyChanged("rowHeigth");
}
}
public ICommand AddCommand { protected set; get; }
public letterviewmodel()
{
letters = new ObservableCollection<lettermodel>()
{
new lettermodel(){TypeLetter="A",Name="letter 1",Date="2021-01-01"},
new lettermodel(){TypeLetter="B",Name="letter 2",Date="2021-01-01"},
new lettermodel(){TypeLetter="C",Name="letter 3",Date="2021-01-01"}
};
rowHeigth = letters.Count * 100 ;
AddCommand = new Command<lettermodel>(async (key) => {
letters.Add(new lettermodel() { TypeLetter = "D", Name = "test letter ", Date = "2021-01-01" });
rowHeigth = letters.Count * 100 ;
});
}
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
public class lettermodel
{
public string TypeLetter { get; set; }
public string Name { get; set; }
public string Date { get; set; }
}
Don't forget toimplement INotifyPropertyChanged interface, to inotify data update.
I have a listview in the content view,and I want to after refreshing hide a part of the page.Please help me to it.I tried to make a swipe but listview conflict with it.so I decided to try make with refresh
<ContentView.Content>
<controls:CustomFrame CornerRadius="25,25,0,0" Margin="0" Padding="10" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
<StackLayout Padding="0">
<BoxView HorizontalOptions="Center" WidthRequest="40" HeightRequest="7" BackgroundColor="Gray" CornerRadius="15" />
<!-- <StackLayout.GestureRecognizers>
<SwipeGestureRecognizer Direction="Up" Command="{Binding RefreshCommand}" ></SwipeGestureRecognizer>
</StackLayout.GestureRecognizers>-->
<ListView ItemsSource="{Binding MyPins}" RowHeight="100" x:Name="ListPlaces" IsPullToRefreshEnabled="True" RefreshCommand="{Binding RefreshCommand}"
IsRefreshing="{Binding IsRefreshing}"
SelectionMode="None">
<ListView.ItemTemplate >
<DataTemplate>
<ViewCell>
<ViewCell.View>
<Frame CornerRadius="10" BackgroundColor="LightBlue" Padding="10">
<StackLayout Orientation="Vertical" Padding="0">
<StackLayout.GestureRecognizers>
<TapGestureRecognizer CommandParameter="{Binding .}" Command="{Binding BindingContext.CallPlace, Source={x:Reference ListPlaces}}" ></TapGestureRecognizer>
</StackLayout.GestureRecognizers>
<Label x:Name="NameOfPlace" Text="{Binding Name}" TextColor="#2D78FD" FontSize="14" FontFamily="Robobo"/>
<Label x:Name="AdressOfPlace" Text="{Binding Address}" TextColor="#616161" FontSize="12" FontFamily="Robobo"/>
<StackLayout Orientation="Horizontal">
<Label x:Name="TimeWork" VerticalOptions="Center" Text="Open until - " TextColor="#616161" FontSize="12" FontFamily="Robobo"/>
<Label x:Name="TimeWork1" VerticalOptions="Center" Text="{Binding Opened}" TextColor="#616161" FontSize="12" FontFamily="Robobo"/>
<Image Source="openIcon" VerticalOptions="Center" />
<Button HeightRequest="24" VerticalOptions="Center" Padding="0,-3,0,0" WidthRequest="92" HorizontalOptions="EndAndExpand" FontSize="14" CornerRadius="45" BackgroundColor="#2D78FD" TextColor="White" Text="Call up"/>
</StackLayout>
</StackLayout>
</Frame>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</controls:CustomFrame>
</ContentView.Content>
WHAT I WANT TO DO
Since you had used MVVM , there are many ways which can implements .
Option 1 :
We could set the IsVisible property of the ViewCell
in xaml
Define the property in the model
public class YourModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
bool isVisible;
public bool IsVisible
{
get
{
return isVisible;
}
set
{
if(value!=isVisible)
{
isVisible = value;
OnPropertyChanged("IsVisible");
}
}
//other property like name...
}
In ViewModel
CallPlace = new Command((org)=> {
YourModel model = org as YourModel;
model.isVisible = false;
});
Option 2
You could remove the item from MyPins
CallPlace = new Command((org)=> {
YourModel model = org as YourModel;
MySource.Remove(model);
});
i need your help i'm trying to make the following UI in xamarin forms.i want the Upload button or image at the end of list . i tried to use collection view with grid item layout .i'm able to show images like this but i can't add upload image at the end like the following . i tried to put upload image/button in the footer of collection view but it appears in bottom of the list not in next to last image . So is there any body who can help me or guide me to achieve this?
Sample UI
<CollectionView x:Name="imgcollection" Margin="5"
BackgroundColor="Transparent" MinimumHeightRequest="15" HeightRequest="150"
ItemsSource="{Binding ItemImages}"
>
<CollectionView.ItemsLayout>
<GridItemsLayout Orientation="Vertical"
Span="{OnIdiom Tablet='6',Phone='4'}" HorizontalItemSpacing="1"
VerticalItemSpacing="2" >
</GridItemsLayout>
</CollectionView.ItemsLayout>
<CollectionView.EmptyView>
<StackLayout >
<Image Source="picturemessage_2.png" Aspect="AspectFill"
HeightRequest="150" WidthRequest="150" HorizontalOptions="Start">
</Image>
</StackLayout>
</CollectionView.EmptyView>
<CollectionView.ItemTemplate>
<DataTemplate>
<ContentView Padding="5" Margin="30" HeightRequest="100" WidthRequest="150">
<AbsoluteLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
<Image x:Name="imgview" Source="{Binding .}" HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand" Aspect="AspectFill"
AbsoluteLayout.LayoutBounds="0,0,1,1"
AbsoluteLayout.LayoutFlags="All"/>
<Image Source="moreoptionbtn.png" Aspect="AspectFill" IsVisible="{OnIdiom Tablet='True',Phone='False'}"
AbsoluteLayout.LayoutBounds="1,0.1,30,30"
AbsoluteLayout.LayoutFlags="PositionProportional"/>
</AbsoluteLayout>
</ContentView>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
C#
private List<ImageSource> itemImages;
public List<ImageSource> ItemImages
{
get { return itemImages; }
set { itemImages = value;
OnPropertyChanged("ItemImages");
}
}
public ImageSource defultImage { get; set; } = "picturemessage_2.png";
public bool Isadd { get; set; } = false;
//
void somefunction()
{
DetailPageViewModel.ItemImages.Add(picture);
DetailPageViewModel.ItemImages.OrderByDescending(s=>s);
var i = DetailPageViewModel.Isadd;
if (!i)
{
DetailPageViewModel.ItemImages.Add(defultImage);
DetailPageViewModel..Isadd = true;
}
}
output
According to your description, you want to click the Collectionview Item image to add image, but making the Upload image always stay on the last item, am I right?
If yes, I do one sample that you can take a look:
<CollectionView ItemsSource="{Binding ItemImages}" SelectionMode="Single">
<CollectionView.ItemsLayout>
<GridItemsLayout Orientation="Vertical" Span="4" />
</CollectionView.ItemsLayout>
<CollectionView.EmptyView>
<StackLayout>
<Image
Aspect="AspectFill"
HeightRequest="150"
Source="image3.png"
WidthRequest="150" />
</StackLayout>
</CollectionView.EmptyView>
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout>
<Image Margin="5" Source="{Binding .}">
<Image.GestureRecognizers>
<TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped" />
</Image.GestureRecognizers>
</Image>
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
Adding GestureRecognizers for Image control, then detecting if the last item image is clicked.
public partial class Page6 : ContentPage
{
public ObservableCollection<ImageSource> ItemImages { get; set; }
public Page6()
{
InitializeComponent();
ItemImages = new ObservableCollection<ImageSource>()
{
"a5.jpg","a6.jpg","a7.jpg","a8.jpg","a9.jpg","upload2.jpg"
};
this.BindingContext = this;
}
private void TapGestureRecognizer_Tapped(object sender, EventArgs e)
{
Image image = (Image)sender;
if (getimagesource(image.Source)!=null && getimagesource(image.Source) == "upload2.jpg")
{
int count = ItemImages.Count;
ItemImages.Insert(count - 1, "a11.jpg");
}
}
private string getimagesource(ImageSource img)
{
string path;
if (img is Xamarin.Forms.FileImageSource)
{
Xamarin.Forms.FileImageSource objFileImageSource = (Xamarin.Forms.FileImageSource)img;
//
// Access the file that was specified:-
path = objFileImageSource.File;
return path;
}
return null;
}
}
The screenshot:
You can make use of DataTemplateSelector and map the last item to upload image or button
public class MyTemplateSelector : DataTemplateSelector
{
public DataTemplate DefaultTemplate { get; set; }
public DataTemplate UploadTemplate { get; set; }
protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
{
var currentItem = ((BindingItemType)item);
var template = currentItem.Equals((container as CollectionView).ItemsSource.Cast<BindingItemType>().LastOrDefault()) ? DefaultTemplate : UploadTemplate;
return template;
}
}
<ContentPage.Resources>
<DataTemplate x:Name="default">
<ContentView Padding="5" Margin="30" HeightRequest="100" WidthRequest="150">
<AbsoluteLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
<Image x:Name="imgview" Source="{Binding .}" HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand" Aspect="AspectFill"
AbsoluteLayout.LayoutBounds="0,0,1,1"
AbsoluteLayout.LayoutFlags="All"/>
<Image Source="moreoptionbtn.png" Aspect="AspectFill" IsVisible="{OnIdiom Tablet='True',Phone='False'}"
AbsoluteLayout.LayoutBounds="1,0.1,30,30"
AbsoluteLayout.LayoutFlags="PositionProportional"/>
</AbsoluteLayout>
</ContentView>
</DataTemplate>
<DataTemplate x:Name="uploadtemplate" >
<Button Text="Upload" Clicked="UploadClicked"/>
</DataTemplate>
<local:MyTemplateSelector DefaultTemplate="{StaticResource default}"
UploadTemplate="{StaticResource uploadtemplate}"
x:Name="templateselector" />
</ContentPage.Resources>
<CollectionView ItemsSource="{Binding ItemImages}" SelectionMode="Single" ItemTemplate="{StaticResource templateselector}">
<CollectionView.ItemsLayout>
<GridItemsLayout Orientation="Vertical" Span="4" />
</CollectionView.ItemsLayout>
<CollectionView.EmptyView>
<StackLayout>
<Image
Aspect="AspectFill"
HeightRequest="150"
Source="image3.png"
WidthRequest="150" />
</StackLayout>
</CollectionView.EmptyView>
</CollectionView>
private void UploadClicked(object sender, EventArgs args)
{
//handle image upload and update the ItemsSource count.
}
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>