Group Swtich Xamarin forms - xamarin

I have a Listview that is creating dynamically data and a switch in every row, what i want is when i toggle a switch the others untoggle.
Is this possible to do?
Example:
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="6*"></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Label Text="{Binding article_description}"
FontAttributes="Bold" FontSize="13" Margin="10,5,0,-6" Grid.Row="0" LineBreakMode="NoWrap"/>
<Label Text="{Binding dish_name}"
FontSize="13" Margin="10,0,0,2" Grid.Row="1" Grid.Column="0"/>
<Label Grid.Row="0" Grid.Column="0" x:Name="LabelReserved" Text="{Binding reserved}" IsVisible="false" LineBreakMode="NoWrap"/>
<Switch Grid.Row="0" Grid.RowSpan="2" Grid.Column="1" HorizontalOptions="Start" VerticalOptions="Center" IsEnabled="False" Toggled="SwitchMenu_OnToggled" >
<Switch.Triggers>
<DataTrigger TargetType="Switch" Binding="{Binding Source={x:Reference LabelReserved},
Path=Text.Length}" Value="7">
<Setter Property="IsToggled" Value="true" />
</DataTrigger>
</Switch.Triggers>
</Switch>
</Grid>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>

Note: This solution was a bit of an experiment on my part - so I would recommend that, if you decide to implement this, use it with caution.
The intent here is to extend Switch to be able to act as a grouped radio button.
First step would be to create a IsToggled or IsChecked or similar property in the item that acts as BindingContext to each list-item. You can implement an interface like:
public interface IToggableItem
{
string GroupName { get; } //not mandatory, only added to support grouped lists
bool IsChecked { get; set; }
}
Second step would be extend Switch to be aware of items-list. We can do that by adding a GroupContext bindable property - which basically represents the parent list-view's ItemsSource.
When a switch is toggled, it iterates through the items-list to set the property as false on other items.
For example:
public class GroupedSwitch : CustomSwitch
{
public static readonly BindableProperty IsGroupingEnabledProperty =
BindableProperty.Create(
"IsGroupingEnabled", typeof(bool), typeof(GroupedSwitch),
defaultValue: default(bool));
public bool IsGroupingEnabled
{
get { return (bool)GetValue(IsGroupingEnabledProperty); }
set { SetValue(IsGroupingEnabledProperty, value); }
}
public static readonly BindableProperty GroupContextProperty =
BindableProperty.Create(
"GroupContext", typeof(IEnumerable), typeof(GroupedSwitch),
defaultValue: default(IEnumerable));
public IEnumerable GroupContext
{
get { return (IEnumerable)GetValue(GroupContextProperty); }
set { SetValue(GroupContextProperty, value); }
}
protected override void OnPropertyChanged(string propertyName = null)
{
base.OnPropertyChanged(propertyName);
if (propertyName != nameof(IsToggled))
return;
if (IsToggled != true || GroupContext == null)
return;
var currentItem = BindingContext as IToggableItem;
if (currentItem == null)
return;
if (IsGroupingEnabled)
{
var groupList = GroupContext as IEnumerable<IGrouping<string, IToggableItem>>;
var currentGroup = groupList.FirstOrDefault(x => x.Key == currentItem.GroupName);
if (currentGroup != null)
foreach (var item in currentGroup)
{
if (item != currentItem)
item.IsChecked = false;
}
}
else
{
var simpleList = GroupContext as IEnumerable<IToggableItem>;
if (simpleList != null)
foreach (var item in simpleList)
{
if (item != currentItem)
item.IsChecked = false;
}
}
}
}
Third step would be bind GroupContext property to parent ListView's items source. For example:
<ListView x:Name="ParentListView" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal" VerticalOptions="Center">
<Label Text="{Binding Name}" />
<local:GroupedSwitch
IsToggled="{Binding IsChecked}"
GroupContext="{Binding ItemsSource, Source={x:Reference ParentListView}}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Or,
<ListView x:Name="_parentList" IsGroupingEnabled="true" >
<ListView.GroupHeaderTemplate>
<DataTemplate>
<TextCell Text="{Binding Key}" />
</DataTemplate>
</ListView.GroupHeaderTemplate>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<Label Text="{Binding Name}" />
<local:GroupedSwitch
ToggledStateFromCode="{Binding IsSwitchOn}"
IsGroupingEnabled="true"
GroupContext="{Binding ItemsSource, Source={x:Reference _parentList}}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
EDIT 1: Updated code to add support for grouped list.

You should use triggers on each switch. Check this out:
https://www.tutorialspoint.com/xaml/xaml_triggers.htm

Related

Change item control property of checked listview item Xamarin.Forms

Hy,
I am trying to show a comment input if the item checkbox is checked and hide it else, i have this XAML
<ListView ItemsSource="{Binding TaskItems}" x:Name="TasksItems" HasUnevenRows="True" VerticalScrollBarVisibility="Default" SelectionMode="None">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout IsVisible="True" Orientation="Vertical">
<Grid BackgroundColor="White">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
</Grid.RowDefinitions>
<StackLayout Grid.Column="0" Grid.Row="0">
<input:CheckBox Type="Box" IsChecked="{Binding TaskChecked , Mode=TwoWay}"/>
</StackLayout>
<StackLayout Grid.Column="0" Grid.Row="1" IsVisible="{Binding CommentRequired}">
<Entry BackgroundColor="White" PlaceholderColor="Black" HeightRequest="40" TextColor="Black"/>
</StackLayout>
</Grid>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
and i have this c# code to read the items from database
public class TaskData
{
public bool TaskChecked { get; set; }
public bool CommentRequired { get; set; }
}
public partial class HomePage : ContentPage
{
public HomePage()
{
ObservableCollection<TaskData> TaskItems { get; set; }
ObservableCollection<TaskData> TasksList;
TaskItems = new ObservableCollection<TaskData>();
//Loop the tasks from database result
While...
TaskItems.Add(new TaskData
{
TaskChecked = false,
CommentRequired = false,
});
//End Loop
TasksListView.ItemsSource = TaskItems;
}
}
Now i need to add a "CheckChanged" event to show the comment Entry (IsVisible="True") when the user check the checkbox of the targed listview item
Thanks
First add the event.
<input:CheckBox Type="Box" IsChecked="{Binding TaskChecked , Mode=TwoWay}" CheckedChanged="OnCheckBoxCheckedChanged"/>
Add Name for the second stack
<StackLayout x:Name="StackLayoutEntry" Grid.Column="0" Grid.Row="1" IsVisible="{Binding CommentRequired}">
<Entry BackgroundColor="White" PlaceholderColor="Black" HeightRequest="40" TextColor="Black"/>
</StackLayout>
Then in code Behind use this function to find the entry for the clicked checkbox
void OnCheckBoxCheckedChanged(object sender, CheckedChangedEventArgs e)
{
var Sender = (CheckBox)sender;
var stacklayoutentry = Sender.Parent.FindByName<StackLayout>("StackLayoutEntry");
stacklayoutentry.IsVisible = True;
}
This might also help you also Check
Another approach but you an identifier to your selected item.
Check

At a time only one expander expand on xamarin form

On my page there is a 4 expander ,I want to write a code for at a time one expander is expand ,What can I do for this scenario please help me ,For more clarifications I have a add image of expanders ,In this given code there is a one expander show ,but this type of a 4 expander available on my page and i want to expand one at a time
enter image description here
<StackLayout IsVisible="{Binding Synonyms,Converter={x:StaticResource CorrectionTypeVisiableConverter}}" Orientation="Vertical" VerticalOptions="StartAndExpand" HorizontalOptions="FillAndExpand">
<xct:Expander ExpandAnimationEasing="CubicIn"
ExpandAnimationLength="500"
CollapseAnimationEasing="CubicOut"
CollapseAnimationLength="500">
<xct:Expander.Header>
<Frame HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" BorderColor="#F0F0F0" HasShadow="False" >
<StackLayout Orientation="Horizontal" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
<xct:BadgeView Text="{Binding Synonyms,Converter={StaticResource CorrectionCountBadgeConverter}}" BackgroundColor="#FADBD8" BadgePosition="TopLeft" TextColor="#E74C3C" HorizontalOptions="Start" FontSize="16" AutoHide="True" VerticalOptions="CenterAndExpand">
<Label Text=""></Label>
</xct:BadgeView>
<Label Text="{x:Static resources:AppResources.Synonyms}"
FontAttributes="Bold" VerticalOptions="CenterAndExpand"
FontSize="Medium" Style="{StaticResource MenueLableStyle}" HorizontalOptions="StartAndExpand" />
<Image Source="Expand.png"
HorizontalOptions="EndAndExpand"
VerticalOptions="CenterAndExpand">
<Image.Triggers>
<DataTrigger TargetType="Image"
Binding="{Binding Source={RelativeSource AncestorType={x:Type xct:Expander}}, Path=IsExpanded,Mode=OneTime}"
Value="True">
<Setter Property="Source"
Value="collapse.png" />
</DataTrigger>
</Image.Triggers>
</Image>
</StackLayout>
</Frame>
</xct:Expander.Header>
<xct:Expander.ContentTemplate>
<DataTemplate>
<StackLayout BindableLayout.ItemsSource="{Binding Synonyms}" VerticalOptions="StartAndExpand" HorizontalOptions="FillAndExpand">
<BindableLayout.ItemTemplate>
<DataTemplate>
<Frame HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" BorderColor="#F0F0F0" HasShadow="False" >
<Grid >
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<StackLayout Grid.Row="0" Orientation="Horizontal">
<Label Text="{Binding s}" HorizontalOptions="Start" VerticalOptions="Center">
</Label>
<Label Text="--->" HorizontalOptions="Start" VerticalOptions="Center"></Label>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<xct:BadgeView Grid.Column="0" Text="" BackgroundColor="#FADBD8" BadgePosition="TopRight" TextColor="#E74C3C" FontSize="14" HorizontalOptions="CenterAndExpand" AutoHide="True" VerticalOptions="Center" Background="#FADBD8" WidthRequest="80" HeightRequest="25">
<Label Text="{Binding c}"></Label>
</xct:BadgeView>
<ImageButton Grid.Column="0" Source="Storyedit.png"
HorizontalOptions="EndAndExpand" VerticalOptions="Center" WidthRequest="12" HeightRequest="12"/>
</Grid>
<ImageButton Source="Info.png" Command="{Binding Path=BindingContext.CorrectionInfoCommand,Source={x:Reference Name=storyView}}"
CommandParameter="{Binding .}" HorizontalOptions="EndAndExpand"/>
</StackLayout>
<Button Grid.Row="1" Text="{x:Static resources:AppResources.IgnoreButton}" Style="{StaticResource CancelButton}" VerticalOptions="EndAndExpand" HorizontalOptions="CenterAndExpand" ></Button>
<Button Grid.Row="1" Text="{x:Static resources:AppResources.AcceptButton}" Style="{StaticResource AcceptButton}" VerticalOptions="EndAndExpand" HorizontalOptions="StartAndExpand" ></Button>
<FlexLayout IsVisible="False" Grid.Row="3" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" AlignItems="Start" AlignContent="Center" Direction="Row" Wrap="Wrap" JustifyContent="Center">
<Button Text="{x:Static resources:AppResources.IgnoreButton}" Padding="5" Style="{StaticResource CancelButton}" HorizontalOptions="StartAndExpand"></Button>
<Button Text="{x:Static resources:AppResources.IgnoreAllButton}" Style="{StaticResource CancelButton}" HorizontalOptions="CenterAndExpand" Padding="5"></Button>
<Button Text="{x:Static resources:AppResources.AcceptButton}" Style="{StaticResource AcceptButton}" HorizontalOptions="StartAndExpand" Padding="5"></Button>
<Button Text="{x:Static resources:AppResources.AcceptAllButton}" Style="{StaticResource AcceptButton}" HorizontalOptions="CenterAndExpand" Padding="5"></Button>
</FlexLayout>
</Grid>
</Frame>
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
</DataTemplate>
</xct:Expander.ContentTemplate>
</xct:Expander>
</StackLayout>
You could binding true or false for the IsExpanded property to indicate that the Expander is expanded or collapsed.
I make a simple example for your reference.
Model:
public class Model : INotifyPropertyChanged
{
#region fields
public string _synonyms;
public string _s;
public bool _isexpand;
#endregion
public string Synonyms
{
get { return _synonyms; }
set { _synonyms = value; OnPropertyChanged("Synonyms"); }
}
public string s
{
get { return _s; }
set { _s = value; OnPropertyChanged("s"); }
}
public bool ISexpand
{
get { return _isexpand; }
set { _isexpand = value; OnPropertyChanged("ISexpand"); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
ViewModel:
public class ViewModel1
{
public ObservableCollection<Model> models { get; set; }
public ViewModel1()
{
CreateCollection();
}
public void CreateCollection()
{
models = new ObservableCollection<Model>()
{
new Model(){ Synonyms="Synonym1", s="A", ISexpand=false},
new Model(){ Synonyms="Synonym2", s="B",ISexpand=false},
new Model(){ Synonyms="Synonym3", s="C",ISexpand=false},
new Model(){ Synonyms="Synonym4", s="D",ISexpand=false},
new Model(){ Synonyms="Synonym5", s="E",ISexpand=false},
};
}
}
Xaml:
<ContentPage.BindingContext>
<local:ViewModel1></local:ViewModel1>
</ContentPage.BindingContext>
<ContentPage.Content>
<StackLayout x:Name="stacklayout" BindableLayout.ItemsSource="{Binding models}" Orientation="Vertical" VerticalOptions="StartAndExpand" HorizontalOptions="FillAndExpand">
<BindableLayout.ItemTemplate>
<DataTemplate>
<xct:Expander IsExpanded="{Binding ISexpand}" Tapped="Expander_Tapped" >
<xct:Expander.Header>
<Label Text="{Binding Synonyms}"></Label>
</xct:Expander.Header>
<xct:Expander.ContentTemplate>
<DataTemplate>
<Label Text="{Binding s}"></Label>
</DataTemplate>
</xct:Expander.ContentTemplate>
</xct:Expander>
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
</ContentPage.Content>
Code behind:
public partial class Page10 : ContentPage
{
ViewModel1 viewModel1=new ViewModel1();
public Page10()
{
InitializeComponent();
}
int i = 0;
private void Expander_Tapped(object sender, EventArgs e)
{
var expander = sender as Expander;
var label = expander.Header as Label;
var list = viewModel1.models;
foreach (var item in viewModel1.models)
{
if (item.Synonyms == label.Text)
{
item.ISexpand = true;
if (i >= 1)
{
foreach (var item1 in viewModel1.models.ToList())
{
if (item1.Synonyms!= label.Text)
{
item1.ISexpand = false;
}
}
BindableLayout.SetItemsSource(stacklayout, viewModel1.models);
}
}
}
i++;
}
}
OutPut:
https://imgur.com/4D6x1yB

Xamarin.forms - checkbox trigger another checkbox's CheckedChanged event

In my xamarin.forms app, I have a listview with checkboxes for the selection of the individual cell. What I am trying to do is multi select the checkboxes inside the listview by providing a "select all" checkbox outside the listview.The Multiselection works fine. For the "select all" checkbox click and individual checkbox click, I am performing some actions like an API Call. The Problem I am facing is Whenever I Click on the "select all" checkbox, the checkbox changed event of individual checkbox gets triggered.I know its natural But is there any way to prevent it like subscribe or unsubscribe the changed event of individual checkbox or something?
Xaml
<Grid >
<Grid.RowDefinitions>
<RowDefinitions Height="Auto"/>
<RowDefinitions Height="Auto"/>
</Grid.RowDefinitions>
<StackLayout Grid.Row="0" Orientation="Horizontal">
<Label Text="Select All" FontSize="Micro" TextColor="LawnGreen" HorizontalOptions="Start" VerticalOptions="Center" >
</Label>
<CheckBox x:Name="MultiselectCheckbox" ScaleX="0.8" ScaleY="0.8" CheckedChanged="MultiSelectCheckBox_CheckedChanged" IsChecked="False" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" Color="LawnGreen"></CheckBox>
</StackLayout>
<ListView
x:Name="Listview"
HorizontalOptions="FillAndExpand"
ItemTapped="DistrictList_ItemTapped"
VerticalOptions="FillAndExpand" >
<ListView.ItemTemplate >
<DataTemplate >
<ViewCell >
<ViewCell.View>
<Frame HorizontalOptions="FillAndExpand">
<StackLayout Orientation="Horizontal" HorizontalOptions="FillAndExpand">
<Label Text="{Binding name}" FontSize="Micro" HorizontalOptions="StartAndExpand" VerticalOptions="Center" TextColor="Snow" Margin="5,0,0,0">
</Label>
<CheckBox CheckedChanged="Single_CheckedChanged" IsChecked="{Binding Selected}" Color="LightBlue" HorizontalOptions="End" >
</CheckBox>
</StackLayout>
</Frame>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
Multiselect Checkbox checked event
private void MultiSelectCheckBox_CheckedChanged(object sender, CheckedChangedEventArgs e)
{
if (!e.Value)
{
foreach (MyData TS in MyObject)
{
TS.Selected = false;
}
}
else{
foreach (MyData TS in MyObject)
{
TS.Selected = true;
}
PerformSomeAction();
}
}
Single selection Checkbox changed event
private void Single_CheckedChanged(object sender, CheckedChangedEventArgs e)
{
if (!e.Value)
{
}
else{
PerformSomeAction();
}
}
Data Model
public class MyData : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public string name { get; set; }
private bool selected;
public bool Selected
{
get
{
return selected;
}
set
{
if (value != null)
{
selected = value;
NotifyPropertyChanged("Selected");
}
}
}
}
Agree with # Nikhileshwar , you could define some properties to get the different condition .And since you had used MVVM, you would better put all logic handling in your viewmodel .
in xaml
<Grid >
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<StackLayout Grid.Row="0" Orientation="Horizontal" HeightRequest="40" BackgroundColor="LightPink">
<Label Text="Select All" FontSize="Micro" TextColor="Red" HorizontalOptions="Start" VerticalOptions="Center" >
</Label>
<CheckBox x:Name="MultiselectCheckbox" ScaleX="0.8" ScaleY="0.8" IsChecked="{Binding MultiselectCheck}" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" Color="Red"></CheckBox>
</StackLayout>
<ListView Grid.Row="1"
x:Name="Listview"
HorizontalOptions="FillAndExpand"
ItemsSource="{Binding MyItems}"
VerticalOptions="FillAndExpand" >
<ListView.ItemTemplate >
<DataTemplate >
<ViewCell >
<Frame Padding="0" HeightRequest="40" HorizontalOptions="FillAndExpand">
<StackLayout Orientation="Horizontal" HorizontalOptions="FillAndExpand">
<Label Text="{Binding name}" FontSize="Micro" HorizontalOptions="StartAndExpand" VerticalOptions="Center" TextColor="Red" Margin="5,0,0,0">
</Label>
<CheckBox IsChecked="{Binding Selected}" Color="Red" HorizontalOptions="End" >
</CheckBox>
</StackLayout>
</Frame>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
in ViewModel
public class MyViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
bool isMultiselect;
bool isSingleSelect;
public ObservableCollection<MyData> MyItems { get; set; }
private bool multiselectCheck;
public bool MultiselectCheck
{
get
{
return multiselectCheck;
}
set
{
if (multiselectCheck != value)
{
multiselectCheck = value;
if(!isSingleSelect)
{
isMultiselect = true;
foreach (MyData data in MyItems)
{
data.Selected = value;
}
isMultiselect = false;
}
NotifyPropertyChanged("MultiselectCheck");
}
}
}
public MyViewModel()
{
MyItems = new ObservableCollection<MyData>() {
new MyData(){name="Selection1" },
new MyData(){name="Selection2" },
new MyData(){name="Selection3" },
};
foreach(MyData data in MyItems)
{
data.PropertyChanged += Data_PropertyChanged;
}
}

How do we bind data to a `footer` in Xamarin Forms

How do we bind data to a footer inside ListView in Xamarin Forms, here I would need to pass the count_in value to footer.
<ListView x:Name="listView">
<ListView.Footer>
<StackLayout>
<Label Text="{Binding Count}" BackgroundColor="Gray"></Label>
</StackLayout>
</ListView.Footer>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="2*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="2*"/>
</Grid.ColumnDefinitions>
<Image Source="{Binding image}" WidthRequest="50" HeightRequest="50" Grid.Column="0" VerticalOptions="Center"/>
<StackLayout Grid.Column="1">
<Label Text="{Binding FullName}" TextColor="#f35e20" HorizontalTextAlignment="Center"/>
</StackLayout>
<StackLayout Grid.Column="2">
<Label Text="{Binding SoccerStatus}" HorizontalTextAlignment="Center" TextColor="#503026"/>
</StackLayout>
<StackLayout Grid.Column="3">
<Label Text="{Binding CurrentDate}" HorizontalTextAlignment="Center" TextColor="#503026"/>
</StackLayout>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Below is the DisplayCount() gets the count from database;
public void DisplayCount()
{
var datetoday = DateTime.Now.ToString("ddMMyyyy");
var count_in = (from x in conn.Table<SoccerAvailability>().Where(x => string.Equals(x.SoccerStatus, "IN", StringComparison.OrdinalIgnoreCase) && x.CurrentDate == datetoday) select x).Count();
}
you are binding to Count
<Label Text="{Binding Count}" BackgroundColor="Gray"></Label>
so Count needs to be a public property on your ViewModel
public int Count { get; set; }
Now getting database exception SQLite exception no such function
equals
This is because SQLLite linq doesn't recognize the string.Equals method. You could convert it to list using ToListAsync for one condition. Then filter the c# list object using equals:
var datetoday = DateTime.Now.ToString("ddMMyyyy");
var items = await conn.Table<SoccerAvailability>().Where(x => x.CurrentDate == datetoday).ToListAsync();
var finalsItems = items.Where(x => string.Equals(x.SoccerStatus, "IN", StringComparison.OrdinalIgnoreCase)).ToList();
Count = finalsItems.Count();
At last, binding your Lable's Text to this Count property.
Edit about binding:
Have you set your content page to your ViewModel? Moreover, implement the INotifyPropertyChanged interface in your view model:
// Set your page's binding context
BindingContext = new PageViewModel();
public class PageViewModel : INotifyPropertyChanged
{
int count;
public int Count
{
set
{
if (count != value)
{
count = value;
onPropertyChanged();
}
}
get
{
return count;
}
}
public event PropertyChangedEventHandler PropertyChanged;
void onPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Edit2:
If you didn't use view model, set a name to your footer label:
<ListView.Footer>
<StackLayout>
<Label x:Name="FooterLabel" BackgroundColor="Gray"></Label>
</StackLayout>
</ListView.Footer>
Then set its value directly:
//...
FooterLabel.Text = finalsItems.Count().ToString();
You need to specify the binding context for the footer.
By default for footers, headers, and templates in a list view, its binding context is going to be the item currently being displayed. So in this case Count would need to be a public property on the item from ItemsSource. Point the Count binding at your view model instead.
<Label Text="{Binding BindingContext.Count, Source={x:Reference xNameSetForCurrentPage}" BackgroundColor="Gray"></Label>
xNameSetForCurrentPage is the x:Name="name" set at the top most element(where all the xmlns stuff is) of the page.

View IsEnabled Property is not working on Xamarin Forms

Here is my Listview
Inside Listview button IsEnabled Property not working,IsEnabled False not working.
I followed This step but still its not working
https://forums.xamarin.com/discussion/47857/setting-buttons-isenabled-to-false-does-not-disable-button
Inside My ViewModel
OrderItems=PopuldateOrders();// getting List Items
<ListView x:Name="OrderItems" VerticalOptions="Fill"
BackgroundColor="White" HasUnevenRows="True"
SeparatorVisibility="None" ItemsSource="{Binding OrderItems}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ContentView BackgroundColor="White">
<Grid BackgroundColor="Transparent" Margin="0" VerticalOptions="FillAndExpand" x:Name="Item">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10*"/>
<ColumnDefinition Width="18*"/>
<ColumnDefinition Width="18*"/>
<ColumnDefinition Width="17*"/>
<ColumnDefinition Width="20*"/>
<ColumnDefinition Width="17*"/>
</Grid.ColumnDefinitions>
<Label Text="{Binding PullSheetId}" Grid.Row="0" IsVisible="False"/>
<controls:CheckBox Checked="{Binding IsChecked}" Grid.Row="0" Grid.Column="0" IsVisible="{Binding IsEnableShipBtn}" Scale=".8"/>
<Label Text="{Binding KitSKU}" Grid.Row="0" Grid.Column="1"
HorizontalTextAlignment="Center" VerticalOptions="Center" FontSize="Small" TextColor="Black"/>
<Label Text="{Binding SKU}" Grid.Row="0" Grid.Column="2"
HorizontalTextAlignment="Center" VerticalOptions="Center" FontSize="Small" TextColor="{Binding ItemColor}"/>
<Label Text="{Binding ReqPackQty}" Grid.Row="0" Grid.Column="3"
HorizontalTextAlignment="Center" VerticalOptions="Center" FontSize="Small" TextColor="Black"/>
<local:EntryStyle Scale=".6" Text="{Binding ScanQuantity}" Grid.Row="0" Keyboard="Numeric"
Grid.Column="4" HorizontalTextAlignment="Center"
VerticalOptions="Center" Placeholder="Qty" IsEnabled="True" x:Name="QtyEntry"
>
<local:EntryStyle.Behaviors>
<eventToCommand:EventToCommandBehavior EventName="TextChanged"
Command="{Binding Source={x:Reference OrderItems}, Path=BindingContext.ChangeItemQty}"
CommandParameter="{Binding Source={x:Reference Item}, Path=BindingContext}"
/>
</local:EntryStyle.Behaviors>
</local:EntryStyle>
<Button Text="Ship" Scale=".6" Grid.Row="0" Grid.Column="5"
VerticalOptions="Center" BackgroundColor="#6eb43a" TextColor="White"
BorderRadius="20" CornerRadius="20" BorderColor="{Binding isError}" BorderWidth="3"
MinimumWidthRequest="60"
x:Name="ShipBtn"
Command="{Binding Source={x:Reference OrderItems}, Path=BindingContext.SubmitSingleItem}"
IsEnabled="{Binding IsEnableShipBtn}" IsVisible="{Binding IsEnableShipBtn}"
CommandParameter="{Binding .}"
/>
</Grid>
</ContentView>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.Behaviors>
<eventToCommand:EventToCommandBehavior EventName="ItemTapped" Command="{Binding PackerItemsItemTapped}"/>
</ListView.Behaviors>
</ListView>
How to solve this?
You could achieve CanExecute method in ICommand to replace the IsEnabled property of Button. You could refer to my demo.
This is a GIF of my demo.
Firstly, You could see MainPage.xaml. Binding the model view and set command for Buttons.
<?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:TestDemo"
x:Class="TestDemo.MainPage">
<!--BindingContext from ButtonExecuteViewModel -->
<StackLayout>
<StackLayout.BindingContext>
<local:ButtonExecuteViewModel/>
</StackLayout.BindingContext>
<Button
Text="click me to enable following button"
Command="{Binding NewCommand}"/>
<Button
Text="Cancel"
Command="{Binding CancelCommand}"/>
</StackLayout>
Here is View Model ButtonExecuteViewModel.cs. You could see the construction method of ButtonExecuteViewModel, it set the execute and canExecute to acheve isEnable of Button.
public class ButtonExecuteViewModel : INotifyPropertyChanged
{
bool isEditing;
public event PropertyChangedEventHandler PropertyChanged;
public ButtonExecuteViewModel()
{
NewCommand = new Command(
execute: () =>
{
IsEditing = true;
RefreshCanExecutes();
},
canExecute: () =>
{
return !IsEditing;
});
CancelCommand = new Command(
execute: () =>
{
IsEditing = false;
RefreshCanExecutes();
},
canExecute: () =>
{
return IsEditing;
});
}
void RefreshCanExecutes()
{
(NewCommand as Command).ChangeCanExecute();
(CancelCommand as Command).ChangeCanExecute();
}
public ICommand NewCommand { private set; get; }
public ICommand CancelCommand { private set; get; }
public bool IsEditing
{
private set { SetProperty(ref isEditing, value); }
get { return isEditing; }
}
//Determine if it can be executed
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));
}
}
I tried all the answers here and nothing worked, I only solved creating a custom button component:
CustomButtonView.xaml
<Button xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="CustomComponents.CustomButton.CustomButtonView"
FontAttributes="Bold"
TextColor="White"
FontSize="20"
TextTransform="Uppercase"
CornerRadius="20"
WidthRequest="200"
HorizontalOptions="Center" />
CustomButtonView.xaml.cs: Here lives the magic of the custom IsEnabled
using System.Windows.Input;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace CustomComponents.CustomButton
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class CustomButtonView
{
#region constructors
public CustomButtonView()
{
InitializeComponent();
BackgroundColor = Color.Blue;
Clicked += (_, args) =>
{
if (IsEnabled) Command?.Execute(args);
};
}
#endregion
#region Command
public new static readonly BindableProperty CommandProperty = BindableProperty.Create(
nameof(Command),
typeof(ICommand),
typeof(CustomButtonView));
public new ICommand? Command
{
get => (ICommand)GetValue(CommandProperty);
set => SetValue(CommandProperty, value);
}
#endregion
#region IsEnabled
public new static readonly BindableProperty IsEnabledProperty = BindableProperty.Create(
nameof(IsEnabled),
typeof(bool),
typeof(CustomButtonView),
true,
propertyChanged: (bindable, _, newValue) =>
{
var component = (CustomButtonView)bindable;
if ((bool)newValue)
{
component.BackgroundColor = Color.Blue;
}
else
{
component.BackgroundColor = Color.Red;
}
});
public new bool IsEnabled
{
get => (bool)GetValue(IsEnabledProperty);
set => SetValue(IsEnabledProperty, value);
}
#endregion
}
}
Now you can use it like any regular button in your XAML:
<customButton:CustomButtonView Text="Button enabled"
Command="{Binding SomeCommand}"
IsEnabled="True"/>
<customButton:CustomButtonView Text="Button disabled"
Command="{Binding SomeCommand}"
IsEnabled="False"/>

Resources