How can we set a default color `#c4bfc7` for row records displaying in the Xamarin forms page - xamarin

Where do we set a default color #c4bfc7 for row records displaying in the page, below is the xaml. Now while tapping, it is showing some color, which is fine. But I want to display some color for rows by default
<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="White" HorizontalTextAlignment="Start"/>
</StackLayout>
<StackLayout Grid.Column="2">
<Label Text="{Binding SoccerStatus}" HorizontalTextAlignment="Center" TextColor="White"/>
</StackLayout>
<StackLayout Grid.Column="3">
<Label Text="{Binding CurrentDate}" HorizontalTextAlignment="Center" TextColor="White"/>
</StackLayout>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>

UPDATE
Your grid inside the ViewCell would look something like below:
<Grid BackgroundColor="#c4bfc7">
First of all, you might wanna add a property for hex code in your model that is bound to your ListView
public class ListModel
{
public string HexCode{get; set;}
}
Now when you are filling this model based on your conditions push in the correct hex code that you want as that items background colour. Once you are done with that your listview would look something like below:
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid BackgroundColor={Binding HexCode}>
Then add a convertor that converts hex to colour:
public class HexToColorConvertor : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string colorHex = (string)value;
if (string.IsNullOrEmpty(colorHex) && string.IsNullOrWhiteSpace(colorHex))
return Color.White;
return Color.FromHex(colorHex); //Note that if the hex code is not valid this might crash
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
// Not implemented as we do not convert back
throw new NotSupportedException();
}
}
Now add this convertor to your resources like below:
<common:HexToColorConvertor x:Key="HexToColor" />
Where common is the namespace of that convertor and then use it like below:
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid BackgroundColor={Binding HexCode, Converter={StaticResource HexToColor}}>

You should set #c4bfc7 background colour to outmost view which is is grid inside view cell here.
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid BackgroundColor="#c4bfc7">
<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="White" HorizontalTextAlignment="Start"/>
</StackLayout>
<StackLayout Grid.Column="2">
<Label Text="{Binding SoccerStatus}" HorizontalTextAlignment="Center" TextColor="White"/>
</StackLayout>
<StackLayout Grid.Column="3">
<Label Text="{Binding CurrentDate}" HorizontalTextAlignment="Center" TextColor="White"/>
</StackLayout>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
Furthermore If you want to change the list view selected item color.
Here is an answer which worked for me. It includes adding few keys to android's style.xml
https://stackoverflow.com/a/38457882/4707196

Related

Catch ExpandableListView group click event in Xamarin Forms

I wish to get selected item for the GroupHeaderTemplate in ExpandableListView. But How to catch ExpandableListView group click event in Xamarin Forms , I am finding Solutions for Xamarin Android but none for the Forms . Moreover List item selection only works for child , How to get clicked event for Group Items. Any Link or Reference would be helpful.
My updated Xaml
<ListView VerticalOptions="FillAndExpand"
x:Name="HotelsList" SeparatorColor="Black"
BackgroundColor="Transparent" ItemSelected="HotelsList_ItemSelected"
IsGroupingEnabled="True"
IsPullToRefreshEnabled="true"
ItemsSource="{Binding StaffLoansList}"
RefreshCommand="{Binding LoadHotelsCommand}" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid VerticalOptions="StartAndExpand" Margin="10" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="30"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<Image Grid.Column="0" Aspect="AspectFit" HeightRequest="20" WidthRequest="30"
HorizontalOptions="StartAndExpand" Margin="5"
VerticalOptions="CenterAndExpand">
<Image.Source>
<FileImageSource File="{Binding ImageStatus}" />
</Image.Source>
</Image>
<Label Grid.Column="1" Text="{Binding actionName}" FontSize="15" HorizontalTextAlignment="Start"
HorizontalOptions="Start"
VerticalOptions="CenterAndExpand" />
<Label Grid.Column="2" Text="{Binding actionDate}" FontSize="15"
HorizontalOptions="EndAndExpand"
VerticalOptions="CenterAndExpand" />
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.GroupHeaderTemplate>
<DataTemplate>
<ViewCell>
<Grid>
<Label
FontSize="16"
Text="{Binding Name}"
TextColor="Gray"
VerticalOptions="Center">
</Label>
<Image x:Name="ImgA" Source="{Binding StateIcon}" Margin="0,0,5,0" HeightRequest="20" WidthRequest="20" HorizontalOptions="End">
<Image.GestureRecognizers>
<TapGestureRecognizer Command="{Binding Path=BindingContext.DummyCommand, Source={x:Reference HotelsList}}" NumberOfTapsRequired="1" CommandParameter="{Binding .}"/>
</Image.GestureRecognizers>
</Image>
<Grid.GestureRecognizers>
<TapGestureRecognizer Command="{Binding Path=BindingContext.ShowDetailCommand, Source={x:Reference HotelsList}}" CommandParameter="{Binding .}"/>
</Grid.GestureRecognizers>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.GroupHeaderTemplate>
</ListView>
ViewModel
In Constructor:
ShowDetailCommand = new Command<StaffLoanPageViewModel>(Showdetail);
ViewModel Class
public ICommand ShowDetailCommand { get; set; }
public void Showdetail(object obj)
{
NavigationService.NavigateTo(ViewModelLocator.StaffLoanDetailPopupPage, Staffloans);
}
That's easy in your first child of ViewCell just add a GestureRecognizor
<ViewCell>
<Grid>
.
.
.
<Grid.GestureRecognizers>
<TapGestureRecognizer Command="{Binding Path=BindingContext.DoSomethingCommand, Source={x:Reference HotelsList}}"
CommandParameter="{Binding .}"/>
</Grid.GestureRecognizers>
</Grid>
</ViewCell>
Then in your command receive this tap event
DoSomethingCommand= new Command(DoSomething);
And your Commands receiver would look something like this:
private void DoSomething(object obj)
{
}
And in this obj object you will get your clicked item's details of the type which is bonded to the ListView, Note this will be a single object and not a collection
Update:
The command property would look something like this:
public ICommand DoSomethingCommand{ get; set; }

AutoScale Label Xamarin

I am working on an app that displays results from a RSS feed. I am trying to show the Title and the Date in the same row of a Stacklayout.
Xaml Code:
StackLayout>
<Label Text="60 Second Sports" FontAttributes="Bold" HorizontalOptions="Center"/>
<ListView x:Name="mainArticleRssList" IsPullToRefreshEnabled="True" Refreshing="ListItems_Refreshing" ItemTapped="RssList_ItemTapped">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Padding="15,0,15,0">
<Label Text="{Binding Title}"
LineBreakMode="WordWrap"
MaxLines="2"/>
<Label Text="{Binding PublishedDate}"
LineBreakMode="WordWrap"
MaxLines="1"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<controls:AdMobView />
</StackLayout>
Here is what it looks like:
What I Expect:
I want the Title to auto scale to fit in the same row as the date. Is it possible to set a width for the entire row and then have the two labels fit inside of the row?
Other fruits of a few hours of googling:
Here are some of the links I found, but some are old and not sure if they work.
This one is old Auto Scale Text Size
This one didn't work Auto-scaling label fontsize in Xamarin
I also found a couple Nuget packages, but i don't think i need to do that.
https://baskren.github.io/Forms9Patch/
https://forums.xamarin.com/discussion/43468/autosize-font-label
Use Grid Layout inside stack layout to achive it
<ListView x:Name="mainArticleRssList" IsPullToRefreshEnabled="True" HasUnevenRows="True" Refreshing="ListItems_Refreshing" ItemTapped="RssList_ItemTapped">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Padding="15,0,15,0">
<Grid x:Name="grd">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="7*"/>
<ColumnDefinition Width="3*"/>
</Grid.ColumnDefinitions>
<Label Text="{Binding Title}"
LineBreakMode="WordWrap"
MaxLines="2"/>
<Label Text="{Binding PublishedDate}" Grid.Column="1"
LineBreakMode="WordWrap"
MaxLines="1"/>
</Grid>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Use this code and it will work for you.
Is that your needs like this screenshot?
You can use Grid to achieved that.
<ContentPage.Content>
<StackLayout>
<Label Text="Xamarin.Forms native cell" HorizontalTextAlignment="Center" />
<ListView x:Name="listView" CachingStrategy="RecycleElement"
ItemSelected="OnItemSelected">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="3*" />
<ColumnDefinition Width="1*" />
</Grid.ColumnDefinitions>
<Label Text="{Binding Title}" Grid.Row="0" Grid.Column="0"
LineBreakMode="TailTruncation"
MaxLines="2" />
<Label Text="{Binding PublishedDate}" Grid.Row="0" Grid.Column="1"
LineBreakMode="WordWrap"
MaxLines="1"/>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
If title is too long, you can setLineBreakMode="TailTruncation" it will automatically truncate when the label reaches the end of the container.

Xamarin form: BindingProperty not setting the property

I am having trouble on my custom control with binding property. It used to be worked when pcl project. After pulling the code out into .net standard 2.0 with latest xamarin form package, it's not working.
This is the setup i have
public static readonly BindableProperty ChildProperty = BindableProperty.Create(nameof(Child), typeof(ChildModel), typeof(ChildModel), null, BindingMode.OneWay, propertyChanging: (BindableObject bindable, object oldValue, object newValue) => {
var a = newValue;
});
and the property is
public ChildModel Child
{
get
{
return (ChildModel)GetValue(ChildProperty);
}
set
{
SetValue(ChildProperty, value);
}
}
I can see newValue does have the childModel data passing in the callback. The GetValue of the second set of code always return null.
<ListView
Style="{StaticResource listStyle}"
AutomationId="listChildren"
CachingStrategy="RecycleElement"
x:Name="childListView"
ItemSelected="OnItemSelected"
ItemTapped="OnItemTapped">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<Frame HasShadow="false" Padding="{StaticResource cellPadding}">
<local:ExtendedFrame Style="{StaticResource cardStyle}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{StaticResource profileGridSize}"></ColumnDefinition>
<ColumnDefinition>*</ColumnDefinition>
</Grid.ColumnDefinitions>
<controls:CircleImage
Grid.Row="0"
Grid.Column="0"
Style="{StaticResource profileImageStyle}"
Source="{Binding Source}"
VerticalOptions="Center"
HorizontalOptions="Center">
</controls:CircleImage>
<StackLayout Orientation="Vertical"
Grid.Row="0"
Grid.Column="1"
VerticalOptions="Center"
HorizontalOptions="Start">
<Label AutomationId="aChildName" Style="{StaticResource MediumBoldFont}" x:Name="childName" Text="{Binding DisplayName}" HorizontalOptions="StartAndExpand" />
<local:ChildInfoIconsView
Child="{Binding .}"
VerticalOptions="Fill">
</local:ChildInfoIconsView>
</StackLayout>
</Grid>
</local:ExtendedFrame>
</Frame>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

List View on binding context change empties the button text

I have been facing this weird behaviour for a while now and I am unable to understand what exactly is causing the problem.
I am using FreshMvvm and I have a ListView with two buttons inside of it.
Now the problem is one of the buttons gets its text from Binding, Secondly to assign the button with a click command I had to follow this.
Now after adding this, the click event works perfectly but the text binding is not working I suspected this happened because of binding context change which I am sure is the whole reason but I am not able to find a way to fix this my listview code is as follows:
<ListView Grid.Row="1"
ItemsSource="{Binding CategoryAndActivities}"
x:Name="WishListName"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Frame>
<Grid VerticalOptions="FillAndExpand"
HorizontalOptions="FillAndExpand">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<!--Image and Title-->
<AbsoluteLayout Grid.Row="0"
HeightRequest="70"
IsClippedToBounds = "true">
<ffimageloading:CachedImage Source="{Binding ActivityImage}"
Aspect="AspectFill"
AbsoluteLayout.LayoutFlags="All"
AbsoluteLayout.LayoutBounds="0.0, 0.0, 0.3, 0.85"
Margin="5, 0, 5, 5"
ErrorPlaceholder="nopreviewlandscape"
LoadingPlaceholder="loadingicon"/>
<Label x:Name="ActivityNameLabel"
Text="{Binding ActivityName}"
FontAttributes="Bold"
VerticalTextAlignment="Start"
TextColor="{StaticResource price_text_color}"
FontSize="Small"
AbsoluteLayout.LayoutFlags="All"
AbsoluteLayout.LayoutBounds="1.0, 0.0, 0.7, 0.85"
Margin="5, 5, 5, 5">
</Label>
</AbsoluteLayout>
<!--Descp-->
<StackLayout Grid.Row = "1"
IsClippedToBounds="true">
<Label Text="{Binding AcitivityDescription}"
FontSize="Small"
LineBreakMode="WordWrap"
Margin="5, 0, 5, 5"/>
</StackLayout>
<Grid BackgroundColor="White"
Grid.Row = "2"
VerticalOptions="FillAndExpand"
HorizontalOptions="FillAndExpand">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50*"/>
<ColumnDefinition Width="50*"/>
</Grid.ColumnDefinitions>
<Button BackgroundColor="{StaticResource ColorBrandingYellow}"
HorizontalOptions="FillAndExpand"
Command="{Binding AddToWishListCommand}"
Grid.Column="0"
BindingContext="{Binding Source={x:Reference ListName}, Path=BindingContext}"
CommandParameter="{Binding Source={x:Reference ActivityNameLabel},Path=BindingContext}"
TextColor="Black"
Text="{resourceLocal:Translate addToWishlist}"
FontSize = "Small" />
<Button BackgroundColor="{StaticResource ColorBrandingYellow}"
HorizontalOptions="FillAndExpand"
Grid.Column="1"
TextColor="Black"
Text="{Binding ActivityAmount}"
FontSize = "Small"
Command="{Binding GoFeatureActivityDetail}"
BindingContext="{Binding Source={x:Reference ListName}, Path=BindingContext}"
CommandParameter="{Binding Source={x:Reference ActivityNameLabel},Path=BindingContext}"/>
</Grid>
</Grid>
</Frame>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
The problem is in the button with binding as text what happems is the text just show empty even though the data actually exist.
The Click event code is as follows:
public ICommand GoFeatureActivityDetail { get; set; }
public BrowseFeaturesPageModel()
{
AddToWishListCommand = new Command(WishListCommand);
GoFeatureActivityDetail = new Command(FeatureActivityDetailCommand);
}
private async void FeatureActivityDetailCommand(object obj)
{}
Right thinking, bad implementation.
What's going on here is that you've changed the Button's BindingContext and now it's not anymore able to "see" the ActivityAmount property of the item 'cause it's 'looking' to the BrowseFeaturesPageModel object.
You can keep the things simpler, changing the BindingContext only where you'll use, not the whole View (the button in this case):
<Button BackgroundColor="{StaticResource ColorBrandingYellow}"
HorizontalOptions="FillAndExpand"
Grid.Column="1"
TextColor="Black"
Text="{Binding ActivityAmount}"
FontSize = "Small"
Command="{Binding BindingContext.GoFeatureActivityDetail, Source={x:Reference ListName}}"
CommandParameter="{Binding .}"/>

Windows 8 - XAML - Conditional background for row in ListView

I have a data source with items in it. Each item has a boolean called "IsAvailable".
I want to render the datasource in a ListView. The background of each row must be green if "IsAvailable" = true or red if "IsAvailable" = false.
How can I do it?
Thanks
-- Marco
This is the code:
<ListView x:Name="frItemlistView" Margin="10,40,666,10" SelectionMode="None" ItemsSource="{Binding Source={StaticResource availableItemsViewSource}}" IsSwipeEnabled="false" IsItemClickEnabled="True" ItemClick="frItemlistView_ItemClick_1" Grid.Row="1" DoubleTapped="frItemlistView_DoubleTapped_1" RightTapped="frItemlistView_RightTapped_1" BorderThickness="35,0,35,35" Grid.RowSpan="2">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Height="110" Margin="6">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="1" VerticalAlignment="Top" Margin="10,0,0,0">
<TextBlock Text="{Binding Title}" Style="{StaticResource TitleTextStyle}" TextWrapping="NoWrap"/>
<TextBlock Text="{Binding Subtitle}" Style="{StaticResource CaptionTextStyle}" TextWrapping="NoWrap"/>
<TextBlock Text="{Binding Volume}" Style="{StaticResource BodyTextStyle}" MaxHeight="60"/>
<TextBlock Text="{Binding IsAvailable}" Style="{StaticResource BodyTextStyle}" MaxHeight="60" />
</StackPanel>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
You can use converter to do conditional formatting of DataTemplate. You need to bind IsAvailable property to background of StackPanel, converter will give appropriate color.
Add a class with this definition.
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Media;
using Windows.UI;
public class AvailabilityToColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
var Availability = (bool)value;
var color = Availability ? new SolidColorBrush(Colors.Green) : new SolidColorBrush(Colors.Red);
return color;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
XAML
local is the XAML namespace reference of AvailabilityToColorConverter class, which is in <Page />
<Page.Resources>
<local:AvailabilityToColorConverter x:Key="AvailabilityToColor" />
</Page.Resources>
<ListView x:Name="frItemlistView" Margin="10,40,666,10" SelectionMode="None" ItemsSource="{Binding Source={StaticResource availableItemsViewSource}}" IsSwipeEnabled="false" IsItemClickEnabled="True" ItemClick="frItemlistView_ItemClick_1" Grid.Row="1" DoubleTapped="frItemlistView_DoubleTapped_1" RightTapped="frItemlistView_RightTapped_1" BorderThickness="35,0,35,35" Grid.RowSpan="2">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Height="110" Margin="6">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="1" VerticalAlignment="Top" Margin="10,0,0,0" Background="{Binding IsAvailable, Converter={StaticResource AvailabilityToColor}}">
<TextBlock Text="{Binding Title}" Style="{StaticResource TitleTextStyle}" TextWrapping="NoWrap"/>
<TextBlock Text="{Binding Subtitle}" Style="{StaticResource CaptionTextStyle}" TextWrapping="NoWrap"/>
<TextBlock Text="{Binding Volume}" Style="{StaticResource BodyTextStyle}" MaxHeight="60"/>
<TextBlock Text="{Binding IsAvailable}" Style="{StaticResource BodyTextStyle}" MaxHeight="60" />
</StackPanel>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

Resources