How can I show 3 column in Xamarin with binding - xamarin

I want to make my grid system like each row has 3 columns. I am binding the products and each product Type, Name and Stock.
Here is my code:
<CollectionView Grid.Row="3" Margin="25" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"
SelectionMode="None" ItemsSource="{Binding AllProducts}" x:Name="ProductsCollection">
<CollectionView.ItemsLayout>
<LinearItemsLayout Orientation="Vertical" ItemSpacing="20"/>
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate>
<pv:PancakeView HasShadow="True" BackgroundColor="#EEF2FF" VerticalOptions="StartAndExpand"
HorizontalOptions="FillAndExpand">
<Grid ColumnSpacing="3" HorizontalOptions="FillAndExpand">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
</Grid.RowDefinitions>
<BoxView Grid.RowSpan="1" BackgroundColor="#EEF2FF"/>
<BoxView Grid.Column="1" Grid.RowSpan="1" BackgroundColor="#EEF2FF"/>
<BoxView Grid.Column="2" Grid.RowSpan="1" BackgroundColor="#EEF2FF"/>
<Button
Text="{Binding Name}"
Grid.Column="0"
HorizontalOptions="Center"
VerticalOptions="Center"
TextColor="Black"
BackgroundColor="#EEF2FF"
/>
</Grid>
</pv:PancakeView>
</DataTemplate>
</CollectionView>
In this way, the products are being shown like each row has one column. So how can I make it 3?
Currently the view is like this:
So what I am trying to achieve is Cola, Water and Soda next to each other.
Here is my product list:
private ObservableCollection<Product> GetProduct()
{
return new ObservableCollection<Product>
{
new Product { Type = "Drink", Name = "Cola", Stock = 123 },
new Product { Type = "Drink", Name = "Water", Stock = 123 },
new Product { Type = "Drink", Name = "Soda", Stock = 123 },
new Product { Type = "Food", Name = "Pizza", Stock = 123 },
new Product { Type = "Food", Name = "Salad", Stock = 123 },
new Product { Type = "Food", Name = "Pasta", Stock = 123 },
new Product { Type = "Drink", Name = "Cola", Stock = 123 },
new Product { Type = "Drink", Name = "Cola", Stock = 123 },
new Product { Type = "Drink", Name = "Cola", Stock = 123 },
new Product { Type = "Food", Name = "Fries", Stock = 123 },
new Product { Type = "Food", Name = "Burger", Stock = 123 },
new Product { Type = "Sauce", Name = "Mayo", Stock = 123 },
new Product { Type = "Sauce", Name = "Ketchup", Stock = 123 },
};
}private ObservableCollection<Product> GetProduct()
{
return new ObservableCollection<Product>
{
new Product { Type = "Drink", Name = "Cola", Stock = 123 },
new Product { Type = "Drink", Name = "Water", Stock = 123 },
new Product { Type = "Drink", Name = "Soda", Stock = 123 },
new Product { Type = "Food", Name = "Pizza", Stock = 123 },
new Product { Type = "Food", Name = "Salad", Stock = 123 },
new Product { Type = "Food", Name = "Pasta", Stock = 123 },
new Product { Type = "Drink", Name = "Cola", Stock = 123 },
new Product { Type = "Drink", Name = "Cola", Stock = 123 },
new Product { Type = "Drink", Name = "Cola", Stock = 123 },
new Product { Type = "Food", Name = "Fries", Stock = 123 },
new Product { Type = "Food", Name = "Burger", Stock = 123 },
new Product { Type = "Sauce", Name = "Mayo", Stock = 123 },
new Product { Type = "Sauce", Name = "Ketchup", Stock = 123 },
};
}
So the Grid.Column needs to be 0, 1, 2 in Row 0 and then when the Row is 1, Grid.Column needs to be 0, 1, 2 again but I dont know is there any dynamic way.
This is what I am trying to achieve:

You want the collectionview to display as a grid which has three columns. So you should need to set <CollectionView.ItemsLayout> as GridItemsLayout. Such as the following code. And the value of the Span means the number of the columns.
<CollectionView HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"
SelectionMode="None" ItemsSource="{Binding AllProducts}" x:Name="ProductsCollection">
<CollectionView.ItemsLayout>
<GridItemsLayout Orientation="Vertical" Span="3" />
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate>
<pv:PancakeView HasShadow="True" BackgroundColor="#EEF2FF" VerticalOptions="StartAndExpand"
HorizontalOptions="FillAndExpand">
<Grid HorizontalOptions="FillAndExpand">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
</Grid.RowDefinitions>
<Button
Text="{Binding Name}"
Grid.Column="0"
HorizontalOptions="Center"
VerticalOptions="Center"
TextColor="Black"
BackgroundColor="#EEF2FF"
/>
</Grid>
</pv:PancakeView>
</DataTemplate>
</CollectionView.ItemTemplate>

Related

Xamarin CarouselView throws OutOfRangeException when ItemsSource changes and Positon is not 0

I have a Xamarin Forms App with a Carousel View and my plan is to filter the result by the Priorities shown in a Bottom Tap Bar.
When the View is on the first card, everything works fine, but if you hit one of the filters from a different card, then the first one, a System.ArgumentOutOfRangeException exception got fired.
I tried already a lot of things to set the position of the Carousel View to 0, but in vain.
using the CarouselView_PositionChanged event => not working
using the TabHost_SelectedTabIndexChanged event => not working
setting the property of the CarouselView by the selectedIndex changed from the Tab View from the ViewModel => not working
turn it into a CollectionView and everything is working => just looks ugly 🤮
Here the 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:android="clr-namespace:Xamarin.Forms.PlatformConfiguration.AndroidSpecific;assembly=Xamarin.Forms.Core"
xmlns:viewModels="clr-namespace:AmsXamarin.ViewModels"
xmlns:fontAwesome="clr-namespace:FontAwesome"
xmlns:cells="clr-namespace:AmsXamarin.Cells"
xmlns:tabs="http://sharpnado.com"
xmlns:xct="http://xamarin.com/schemas/2020/toolkit"
x:Class="AmsXamarin.Views.SnagListX.SnagListPage"
x:Name="mySnagListPage">
<ContentPage.BindingContext>
<viewModels:SnagListViewModel />
</ContentPage.BindingContext>
<ContentPage.Resources>
<ResourceDictionary>
<xct:TabSelectionChangedEventArgs x:Key="TabSelectionChangedEventArgs" />
</ResourceDictionary>
</ContentPage.Resources>
<ContentPage.ToolbarItems>
<ToolbarItem Command="{Binding ShowMyJobsCommand}"
Order="Primary"
Priority="0"
Text="{Binding MyJobsTitle,Mode=TwoWay}">
</ToolbarItem>
<ToolbarItem Command="{Binding AddFaultCommand}"
Order="Primary"
Priority="0">
<ToolbarItem.IconImageSource>
<FontImageSource FontFamily="FAS"
Glyph="{x:Static fontAwesome:FontAwesomeIcons.Plus}"
Color="{AppThemeBinding Dark={StaticResource Third},Light={StaticResource Primary}}"
Size="Large" />
</ToolbarItem.IconImageSource>
</ToolbarItem>
<ToolbarItem Command="{Binding AcceptCommand}"
Order="Primary"
Priority="0">
<ToolbarItem.IconImageSource>
<FontImageSource FontFamily="FAS"
Glyph="{x:Static fontAwesome:FontAwesomeIcons.UserCheck}"
Color="{AppThemeBinding Dark={StaticResource Third},Light={StaticResource Primary}}"
Size="Large" />
</ToolbarItem.IconImageSource>
</ToolbarItem>
</ContentPage.ToolbarItems>
<ContentPage.Content>
<StackLayout>
<Label Style="{StaticResource LabelLarge}"
Text="Snag List"
VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand" />
<StackLayout>
<IndicatorView x:Name="snagListIndicator"
Margin="0,10,0,0"
IndicatorColor="LightGray"
SelectedIndicatorColor="LightGray"
IndicatorSize="6" />
<RefreshView Command="{Binding RefreshCommand}"
IsRefreshing="{Binding IsBusy, Mode=OneWay}"
Style="{StaticResource BaseRefreshView}">
<CarouselView x:Name="snagListCV"
Margin="10"
IndicatorView="snagListIndicator"
ItemsLayout="HorizontalList"
ItemsSource="{Binding SnagListPriorities.SnagListApps}"
CurrentItem="{Binding SnagListItem}"
Position="{Binding PositionIdx,Mode=OneWay}"
PositionChanged="CarouselView_PositionChanged"
Loop="False"
IsEnabled="{Binding IsNotBusy}">
<CarouselView.EmptyView>
<StackLayout Padding="12">
<Label Style="{StaticResource LabelMedium}"
HorizontalOptions="Center"
Text="{Binding EmptyMessage,Mode=TwoWay}" />
</StackLayout>
</CarouselView.EmptyView>
<CarouselView.ItemTemplate>
<DataTemplate>
<cells:SnagListCardX />
</DataTemplate>
</CarouselView.ItemTemplate>
</CarouselView>
</RefreshView>
</StackLayout>
<tabs:TabHostView x:Name="TabHost"
Margin="13,0,13,10"
BackgroundColor="{AppThemeBinding Dark={StaticResource Third},Light={StaticResource Fourth}}"
CornerRadius="30"
IsSegmented="True"
Orientation="Horizontal"
TabType="Fixed"
SelectedIndex="{Binding SelectedIndex,Mode=TwoWay}"
Shades="{StaticResource LightBottomShadow}">
<tabs:TabHostView.Behaviors>
<xct:EventToCommandBehavior EventName="SelectedTabIndexChanged"
Command="{Binding SelectedCommand}"
EventArgsConverter="{StaticResource TabSelectionChangedEventArgs}" />
</tabs:TabHostView.Behaviors>
<tabs:TabHostView.Tabs>
<tabs:BottomTabItem Style="{StaticResource BottomTabsMedium}"
Label="All">
<tabs:BottomTabItem.Badge>
<tabs:BadgeView Style="{StaticResource BadgeViewBase}"
BackgroundColor="{StaticResource All}"
TextColor="White"
Text="{Binding SnagListPriorities.All,Mode=TwoWay}" />
</tabs:BottomTabItem.Badge>
</tabs:BottomTabItem>
<tabs:BottomTabItem Style="{StaticResource BottomTabsMedium}"
Label="High"
StyleClass="">
<tabs:BottomTabItem.Badge>
<tabs:BadgeView Style="{StaticResource BadgeViewBase}"
BackgroundColor="{StaticResource High}"
TextColor="White"
Text="{Binding SnagListPriorities.High,Mode=OneWay}" />
</tabs:BottomTabItem.Badge>
</tabs:BottomTabItem>
<tabs:BottomTabItem Style="{StaticResource BottomTabsMedium}"
Label="Medium">
<tabs:BottomTabItem.Badge>
<tabs:BadgeView Style="{StaticResource BadgeViewBase}"
BackgroundColor="{StaticResource Medium}"
TextColor="Black"
Text="{Binding SnagListPriorities.Medium,Mode=TwoWay}" />
</tabs:BottomTabItem.Badge>
</tabs:BottomTabItem>
<tabs:BottomTabItem Style="{StaticResource BottomTabsMedium}"
Label="Low">
<tabs:BottomTabItem.Badge>
<tabs:BadgeView Style="{StaticResource BadgeViewBase}"
BackgroundColor="{StaticResource Low}"
TextColor="Black"
Text="{Binding SnagListPriorities.Low,Mode=TwoWay}" />
</tabs:BottomTabItem.Badge>
</tabs:BottomTabItem>
</tabs:TabHostView.Tabs>
</tabs:TabHostView>
</StackLayout>
</ContentPage.Content>
</ContentPage>
And the view model
using AmsXamarin.Helpers;
using AmsXamarin.Models;
using AmsXamarin.Services;
using MvvmHelpers;
using MvvmHelpers.Commands;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Xamarin.Forms;
using Command = MvvmHelpers.Commands.Command;
namespace AmsXamarin.ViewModels
{
public class SnagListViewModel : BaseViewModel
{
readonly ISnagListService snagListService;
List<SnagListAppX> SnagListAppXs;
SnagListAppX snagListItem;
public SnagListAppX SnagListItem
{
get { return snagListItem; }
set
{
snagListItem = value;
OnPropertyChanged();
}
}
SnagListPriorities snagListPriorities;
public SnagListPriorities SnagListPriorities
{
get { return snagListPriorities; }
set
{
snagListPriorities = value;
OnPropertyChanged();
}
}
public AsyncCommand AddFaultCommand { get; }
public AsyncCommand AcceptCommand { get; }
public Command RefreshCommand { get; }
public Command SelectedCommand { get; }
public Command ShowMyJobsCommand { get; }
string emptyMessage;
public string EmptyMessage
{
get { return emptyMessage; }
set
{
emptyMessage = value;
OnPropertyChanged();
}
}
int positionIdx;
public int PositionIdx
{
get { return positionIdx; }
set
{
positionIdx = value;
OnPropertyChanged();
}
}
int selectedIndex;
public int SelectedIndex
{
get => selectedIndex;
set => SetProperty(ref selectedIndex, value);
}
string myJobsTitle = "My Jobs";
int staffId;
public string MyJobsTitle
{
get { return myJobsTitle; }
set
{
myJobsTitle = value;
OnPropertyChanged();
}
}
bool myJobsEnabled = true;
bool updateProperty = false;
public bool AcceptToolBar { get; set; }
public SnagListViewModel()
{
SnagListItem = new SnagListAppX();
SnagListPriorities = new SnagListPriorities()
{
SnagListApps = new ObservableRangeCollection<SnagListAppX>()
};
SnagListAppXs = new List<SnagListAppX>();
AddFaultCommand = new AsyncCommand(ShowAddSnagListItem);
AcceptCommand = new AsyncCommand(ShowModalAccept);
SelectedCommand = new Command(Selected);
RefreshCommand = new Command(Refresh);
staffId = 0;
ShowMyJobsCommand = new Command(ShowModalMyJobs);
snagListService = DependencyService.Get<ISnagListService>();
Device.BeginInvokeOnMainThread(async () =>
{
await GetSnagListItems();
});
}
async Task GetSnagListItems()
{
try
{
IsBusy = true;
EmptyMessage = "Loading...";
SnagListPriorities slp = await snagListService.GetSnagLists(false, true);
SnagListPriorities.SnagListApps.Clear();
SnagListPriorities = slp;
SnagListAppXs.Clear();
SnagListAppXs.AddRange(slp.SnagListApps);
EmptyMessage = SnagListAppXs.Count == 0 ? "Good Job! \r\n\r\nCurrently nothing to fix" : "";
IsBusy = false;
}
catch (Exception ex)
{
await Application.Current.MainPage.DisplayAlert("Error", ex.Message, "Ok");
}
}
void Selected()
{
//PositionIdx = 0;
//OnPropertyChanged(nameof(PositionIdx));
//FilterSnagList();
Refresh();
}
void FilterSnagList()
{
var allJobs = SnagListAppXs;
if (staffId != 0) allJobs = allJobs.Where(x => x.StaffId == staffId).ToList();
if (updateProperty) OnPropertyChanged(nameof(SnagListPriorities));
if (selectedIndex > 0) allJobs = allJobs.Where(sli => sli.Priority == selectedIndex).ToList();
SnagListPriorities.SnagListApps.Clear();
//SnagListPriorities.SnagListApps = new ObservableRangeCollection<SnagListAppX>(allJobs);
SnagListPriorities.SnagListApps.AddRange(allJobs);
//OnPropertyChanged(nameof(SnagListPriorities.SnagListApps));
updateProperty = false;
}
void ShowModalMyJobs()
{
staffId = myJobsEnabled ? int.Parse(Settings.StaffIdSetting) : 0;
MyJobsTitle = myJobsEnabled ? "All Jobs" : "My Jobs";
AcceptToolBar = !myJobsEnabled;
myJobsEnabled = !myJobsEnabled;
SelectedIndex = 0;
updateProperty = true;
}
void Refresh()
{
IsBusy = true;
var allJobs = SnagListAppXs.Where(s => s.StaffId == 115);
SnagListPriorities.SnagListApps.Clear();
SnagListPriorities.SnagListApps.AddRange(allJobs);
IsBusy = false;
}
}
}
looks a bit messy, but wanted to show, that I tried already a lot of things.
Last try was a simple RefreshView.
It works as long as the itemsSource is not changing. Once it changes and the first card is not shown, it crashes.
Any ideas? Many thanks

Xamarin: Binding to ImageSource property is not working

I am trying to display images dynamically through binding:
I have ObservableCollection of TabItem to which I load a png into the Icon Property:
TabItems.Add(new TabItem()
{
Title = AppResources.Home,
IsSelected = true,
Icon = ImageSource.FromResource("Home.png")
});
Where:
public class TabItem : BindableObject
{
private bool _isSelected;
public ImageSource Icon { get; set; }
public string Title { get; set; }
public bool IsSelected
{
get
{
return _isSelected;
}
set
{
if (_isSelected != value)
{
_isSelected = value;
OnPropertyChanged();
}
}
}
}
And I have a DataTemplate of TabItem in a CollectionView that displays these items and uses the Icon Property to bind to Image:
<DataTemplate x:DataType="local:TabItem" x:Key="TabItem_DataTemplate">
<StackLayout Orientation="Vertical" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"
WidthRequest="{Binding Title, Converter={StaticResource ProportionateConverter}}"
>
<Image Source="{Binding Icon}" InputTransparent="True" HeightRequest="50" />
<Label HorizontalOptions="Center" VerticalOptions="End" FontSize="Small"
Text="{Binding Title}"
InputTransparent="True"
TextColor="{Binding IsSelected, Converter={StaticResource IsSelectedToTextColorConverter}}"/>
</StackLayout>
</DataTemplate>
I get an Error in runtime:
ImageLoaderSourceHandler: Image data was invalid: Xamarin.Forms.StreamImageSource
The images are in the Resources folder and are marked as Embedded resource
Updated solution:
(Thanks Jason)
The solution was using my markup extension when initializing the Icon property (I'll be glad to hear of a more elegant way)
var homeExt = new ImageResourceExtension()
{
Source = "TimeManager.Resources.Icons.Home.png"
};
TabItems.Add(new TabItem()
{
Title = AppResources.Home,
IsSelected = true,
Icon = (ImageSource)(homeExt.ProvideValue(null))
});

How to change fontsize of listview in xamarin?

This is my code in my edit.cs
var db = new SQLiteConnection(_dbPath);
StackLayout stackLayout = new StackLayout();
_listView = new ListView();
_listView.ItemsSource = db.Table<SpeechRecTable>().OrderBy(x => x.Text).ToList();
_listView.ItemSelected += _listView_ItemSelected;
//_listView.SeparatorColor = Color.WhiteSmoke;
stackLayout.Children.Add(_listView);
_button = new Button();
_button.Text = "UPDATE";
_button.BackgroundColor = Color.Coral;
_button.TextColor = Color.WhiteSmoke;
_button.Clicked += _button_Clicked;
stackLayout.Children.Add(_button);
Content = stackLayout;
I am new in xamarin, and Im trying to create a CRUD application, I am following this tutorial: https://www.youtube.com/watch?v=aabHAgY5VXo&t=58s
I cant seem to customize its font size, this is just a .cs file, not a xaml.cs file
I show you 2 solution.
In C#
public class CustomCell : ViewCell
{
public CustomCell()
{
var nameLabel = new Label();
var verticaLayout = new StackLayout();
var horizontalLayout = new StackLayout();
//set bindings
nameLabel.SetBinding(Label.TextProperty, new Binding("Name"));
nameLabel.FontSize = 24;
//add views to the view hierarchy
verticaLayout.Children.Add(nameLabel);
horizontalLayout.Children.Add(verticaLayout);
// add to parent view
View = horizontalLayout;
}
}
_listView.ItemTemplate = new DataTemplate(typeof(CustomCell));
or in Xaml
<StackLayout>
<ListView x:Name="ItemsListView"
ItemsSource="{Binding Items}"
VerticalOptions="FillAndExpand"
HasUnevenRows="true"
RefreshCommand="{Binding LoadItemsCommand}"
IsPullToRefreshEnabled="true"
IsRefreshing="{Binding IsBusy, Mode=OneWay}"
CachingStrategy="RecycleElement"
ItemSelected="OnItemSelected">
<d:ListView.ItemsSource>
<x:Array Type="{x:Type x:String}">
<x:String>First Item</x:String>
<x:String>Second Item</x:String>
<x:String>Third Item</x:String>
<x:String>Fourth Item</x:String>
<x:String>Fifth Item</x:String>
<x:String>Sixth Item</x:String>
</x:Array>
</d:ListView.ItemsSource>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Padding="10">
<Label Text="{Binding Text}"
d:Text="{Binding .}"
LineBreakMode="NoWrap"
Style="{DynamicResource ListItemTextStyle}"
FontSize="16" />
<Label Text="{Binding Description}"
d:Text="Item descripton"
LineBreakMode="NoWrap"
Style="{DynamicResource ListItemDetailTextStyle}"
FontSize="13" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
Try modifying your code like this,
var db = new SQLiteConnection(_dbPath);
StackLayout stackLayout = new StackLayout();
ListView _listView = new ListView
{
// template for displaying each item.
ItemTemplate = new DataTemplate(() =>
{
Label nameLabel = new Label();
nameLabel.TextColor = Color.Black;
nameLabel.FontSize = 15;
nameLabel.SetBinding(Label.TextProperty, "Name");
return new ViewCell
{
View = new StackLayout
{
Padding = new Thickness(5),
VerticalOptions = LayoutOptions.Center,
Children =
{
nameLabel
}
}
};
})
};
//_listView.SeparatorColor = Color.WhiteSmoke;
_listView.ItemsSource = db.Table<SpeechRecTable>().OrderBy(x => x.Text).ToList();
_listView.ItemSelected += _listView_ItemSelected;
stackLayout.Children.Add(_listView);
_button = new Button();
_button.Text = "UPDATE";
_button.BackgroundColor = Color.Coral;
_button.TextColor = Color.WhiteSmoke;
_button.Clicked += _button_Clicked;
stackLayout.Children.Add(_button);
Content = stackLayout;

Couldn't get basic Hamburger Master Detail view

After looking at all the questions and forums, I'm still unable to get my Master Detail page with Hamburger icon. If i use this Master detail page as application start then I'm seeing the functionality working as expected. Please look at the code below
DashBoadCreator.xaml
`
<MasterDetailPage.Master>
</MasterDetailPage.Master>
<MasterDetailPage.Detail>
</x:Arguments>
</NavigationPage>
</MasterDetailPage.Detail>
`
`public partial class DashBoadCreator : MasterDetailPage
{
DashboardMaster master;
DashboardDetail1 detil;
public DashBoadCreator()
{
InitializeComponent();
master = new DashboardMaster();
detil = new DashboardDetail1();
Master = master;
Master.Title = "this is a title";
Master.Icon = "icon.png";
Detail = new NavigationPage(detil);
}
// Event for Menu Item selection, here we are going to handle navigation based
// on user selection in menu ListView
}`
DashboadMaster.xaml
`
<!--
This StackLayout you can use for other
data that you want to have in your menu drawer
<StackLayout BackgroundColor="#e74c3c"
HeightRequest="75">
<Label Text="Some Text title"
FontSize="20"
VerticalOptions="CenterAndExpand"
TextColor="White"
HorizontalOptions="Center"/>
</StackLayout> -->
<ListView x:Name="navigationDrawerList"
RowHeight="60"
SeparatorVisibility="None"
BackgroundColor="#e8e8e8"
ItemSelected="OnMenuItemSelected">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<!-- Main design for our menu items -->
<StackLayout VerticalOptions="FillAndExpand"
Orientation="Horizontal"
Padding="20,10,0,10"
Spacing="20">
<Image Source="{Binding Icon}"
WidthRequest="40"
HeightRequest="40"
VerticalOptions="Center" />
<Label Text="{Binding Title}"
FontSize="Medium"
VerticalOptions="Center"
TextColor="Black"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
`
` public partial class DashboardMaster : ContentPage
{
public List<MasterPageItem> menuList { get; set; }
public DashboardMaster()
{
Title = "samples";
InitializeComponent();
menuList = new List<MasterPageItem>();
// Creating our pages for menu navigation
// Here you can define title for item,
// icon on the left side, and page that you want to open after selection
var page1 = new MasterPageItem() { Title = "Item 1", Icon = "itemIcon1.png", TargetType = typeof(DashboardDetail1) };
var page2 = new MasterPageItem() { Title = "Item 2", Icon = "itemIcon2.png", TargetType = typeof(DashboardDetail1) };
var page3 = new MasterPageItem() { Title = "Item 3", Icon = "itemIcon3.png", TargetType = typeof(DashboardDetail1) };
var page4 = new MasterPageItem() { Title = "Item 4", Icon = "itemIcon4.png", TargetType = typeof(DashboardDetail1) };
var page5 = new MasterPageItem() { Title = "Item 5", Icon = "itemIcon5.png", TargetType = typeof(DashboardDetail1) };
var page6 = new MasterPageItem() { Title = "Item 6", Icon = "itemIcon6.png", TargetType = typeof(DashboardDetail1) };
var page7 = new MasterPageItem() { Title = "Item 7", Icon = "itemIcon7.png", TargetType = typeof(DashboardDetail1) };
var page8 = new MasterPageItem() { Title = "Item 8", Icon = "itemIcon8.png", TargetType = typeof(DashboardDetail1) };
var page9 = new MasterPageItem() { Title = "Item 9", Icon = "itemIcon9.png", TargetType = typeof(DashboardDetail1) };
// Adding menu items to menuList
menuList.Add(page1);
menuList.Add(page2);
menuList.Add(page3);
menuList.Add(page4);
menuList.Add(page5);
menuList.Add(page6);
menuList.Add(page7);
menuList.Add(page8);
menuList.Add(page9);
// Setting our list to be ItemSource for ListView in MainPage.xaml
navigationDrawerList.ItemsSource = menuList;
//Application.Current.MainPage = new DashboardMaster();
// NavigationPage.SetHasNavigationBar(this, false);
}
private void OnMenuItemSelected(object sender, SelectedItemChangedEventArgs e)
{
DashBoadCreator creator = new DashBoadCreator();
var item = (MasterPageItem)e.SelectedItem;
Type page = item.TargetType;
creator.Detail = new NavigationPage((Page)Activator.CreateInstance(page));
creator.IsPresented = false;
}
}
<ListView.ItemTemplate>
<Image Source="{Binding Icon}"
WidthRequest="40"
HeightRequest="40"
VerticalOptions="Center" />
<Label Text="{Binding Title}"
FontSize="Medium"
VerticalOptions="Center"
TextColor="Black"/>
<!-- <Label Text="{Binding Description}"
FontSize="Small"
VerticalOptions="End"/>-->
<StackLayout VerticalOptions="End" HorizontalOptions="End">
<Button Text="Apply" FontSize="10" TextColor="Green" BorderWidth="1" HorizontalOptions="End" />
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
set icon for master page to see hamburger icon
Sample code :
public masterpage()
{
Icon = "hamburger.png";
}
I coded a working´s demo following a few differents tutos, and getting the most important part of them. So, at least for me, it was a simplier demo I can get it.
Check this link out.
My github working demo
Where Intervection is a random detail page (constructor by parameter).
Let me know aobut any doubt you could have.
Cheers mate. Merry Christmas.
After of some finding I came accorss this discussion
Missing menu button on MasterDetailPage when assigning App.MainPage
Using those findings I changed my app.xaml.cs as follows
MainPage = new NavigationPage(new MenuPage());
MasterDetailTest.App.Current.MainPage.Navigation.PushAsync(new MainPage());
Now the Master page is always the root page and the hamburger menu works as expected. To anyone else having this problem hope this helps you in some way

How to check the check box dynamically in listbox in windows phone 7?

I have the listbox with four checkbox items. If I give the input as 2 then first two check boxes should select,this should happen programatically.
Please help me out..
Thanks,
.xaml page
<StackPanel Background="White" Margin="5,0,5,0">
<ListBox x:Name="listBox2" Foreground="Black" Height="300" SelectionMode="Multiple" SelectionChanged="listBox2_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<StackPanel Name="stackpanel1" Orientation="Horizontal" >
<CheckBox IsChecked="{Binding IsChecked, Mode=TwoWay}" Content="{Binding Name}" Foreground="Black" Height="68" Margin="0,-15,0,-10" BorderThickness="0" Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked">
</CheckBox>
</StackPanel>
<Rectangle Fill="Gray" Height=".5" HorizontalAlignment="Stretch" Width="440" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
.cs code:
List<Items> source = new List<Items>();
source.Add(new Items() { Name = "Item 1" });
source.Add(new Items() { Name = "Item 2" });
source.Add(new Items() { Name = "Item 3" });
source.Add(new Items() { Name = "Item 4" });
source.Add(new Items() { Name = "Item 5" });
source.Add(new Items() { Name = "Item 6" });
`` listBox2.ItemsSource = source;
Items class
public class Items
{
public string Name
{
get;
set;
}
}
Here's a really crude way of doing what I think you've described. It doesn't use much of your code directly but should get you moving in the right direction.
XAML
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<toolkit:ListPicker SelectionChanged="ListPicker_OnSelectionChanged">
<toolkit:ListPickerItem>0</toolkit:ListPickerItem>
<toolkit:ListPickerItem>1</toolkit:ListPickerItem>
<toolkit:ListPickerItem>2</toolkit:ListPickerItem>
<toolkit:ListPickerItem>3</toolkit:ListPickerItem>
<toolkit:ListPickerItem>4</toolkit:ListPickerItem>
</toolkit:ListPicker>
<ItemsControl x:Name="TheListBox" Grid.Row="1" >
<ItemsControl.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsChecked, Mode=TwoWay}" Content="{Binding Name}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
Note that I'm using the Windows Phone Toolkit (get it from http://phone.codeplex.com/ or nuget)
C#
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Controls;
using Microsoft.Phone.Controls;
public partial class MainPage : PhoneApplicationPage
{
ObservableCollection<Items> source = new ObservableCollection<Items>();
public MainPage()
{
InitializeComponent();
source.Add(new Items { Id = 1 });
source.Add(new Items { Id = 2 });
source.Add(new Items { Id = 3 });
source.Add(new Items { Id = 4 });
TheListBox.ItemsSource = source;
}
private void ListPicker_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (source.Count > 0 && e.AddedItems.Count > 0)
{
for (int i = 0; i < source.Count; i++)
{
this.source[i].IsChecked = int.Parse(((ContentControl)(e.AddedItems[0])).Content.ToString()) >= this.source[i].Id;
}
}
}
}
public class Items : INotifyPropertyChanged
{
private bool isChecked;
public int Id { get; set; }
public string Name
{
get
{
return "Item " + this.Id;
}
}
public bool IsChecked
{
get
{
return this.isChecked;
}
set
{
this.isChecked = value;
this.OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}

Resources