How to make a fixed element width (frame or stacklayout) - xamarin

I made a frame on Android Xamarin.Forms using an absoluteLayOut! My goal is to set little space from the device width! But when I try it on two device there was total reduction from the height and and width of the frame..
https://i.stack.imgur.com/8kjzD.jpg
<AbsoluteLayout>
<Frame AbsoluteLayout.LayoutBounds="0.5,0.5,310,340" AbsoluteLayout.LayoutFlags="PositionProportional" CornerRadius="15" Padding="0">
<AbsoluteLayout BackgroundColor="Black">
<Label Text="mos.Softs" FontAttributes="Bold" FontSize="16" TextColor="Wheat"
AbsoluteLayout.LayoutBounds="0.5,0.011" AbsoluteLayout.LayoutFlags="PositionProportional"></Label>
<Label x:Name="lblWidth" FontAttributes="Bold" FontSize="16" TextColor="Wheat"
AbsoluteLayout.LayoutBounds="0.5,0.5" AbsoluteLayout.LayoutFlags="PositionProportional"></Label>
<Button Padding="0" CornerRadius="5" Text="Click me" TextTransform="None"
AbsoluteLayout.LayoutBounds="0.5,0.98, 100,40" AbsoluteLayout.LayoutFlags="PositionProportional"></Button>
</AbsoluteLayout>
</Frame>
</AbsoluteLayout>

You could use the converter to fit the size instead of AbsoluteLayout.
Set the name to your Frame first.
<Frame
…………
x:Name="frame"/>
Create the MyConverter: MyConverter.cs
public class MyConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (double)value / 3.0;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Set the StaticResource:
<ContentPage.Resources>
<ResourceDictionary>
<local:MyConverter x:Key="MyConverter" />
</ResourceDictionary>
</ContentPage.Resources>
Binding for the frame value:
<Frame x:Name="frame" >
<StackLayout BackgroundColor="Gray" VerticalOptions="CenterAndExpand" WidthRequest="{Binding Source={x:Reference frame},Path=Width,Converter={StaticResource MyConverter}}"
HeightRequest="{Binding Source={x:Reference frame},Path=Height,Converter={StaticResource MyConverter}}" >
<Label Text="mos.Softs" FontAttributes="Bold" FontSize="16" TextColor="Wheat"
HorizontalOptions="CenterAndExpand" VerticalOptions="StartAndExpand" ></Label>
<Label Text="Device Height" x:Name="lblWidth" FontAttributes="Bold" FontSize="16" TextColor="Wheat"
HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand"></Label>
<Button Padding="0" CornerRadius="5" Text="Click me" TextTransform="None"
HorizontalOptions="CenterAndExpand" VerticalOptions="EndAndExpand" ></Button>
</StackLayout>
</Frame>

Related

How to get value of swiped card view xamarin

I have a SwipeCardView and I want to get the id of the user that I've just swiped.
<swipeCardView:SwipeCardView
x:Name="SwipeView1" ItemsSource="{Binding Profiles}" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"
Padding="10" >
<swipeCardView:SwipeCardView.ItemTemplate>
<DataTemplate>
<StackLayout HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand">
<Frame CornerRadius="10"
Padding="8"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand">
<AbsoluteLayout>
<AbsoluteLayout.GestureRecognizers>
<SwipeGestureRecognizer Direction="Left" Command="{Binding LeftCommand}"
CommandParameter="{Binding nome}" />
</AbsoluteLayout.GestureRecognizers>
<Image Source="{Binding foto_perfil}"
Aspect="AspectFill"
AbsoluteLayout.LayoutBounds=".5,0.5,1,1"
AbsoluteLayout.LayoutFlags="All" />
<Label FontSize="Large"
WidthRequest="30"
FontAttributes="Bold"
TextColor="White"
BackgroundColor="Black"
AbsoluteLayout.LayoutBounds="0.1,0.95,250,30"
AbsoluteLayout.LayoutFlags="PositionProportional">
<Label.FormattedText>
<FormattedString>
<Span Text="{Binding nome}" />
<Span Text=", " />
<Span Text="{Binding data_nasc}" />
</FormattedString>
</Label.FormattedText>
</Label>
</AbsoluteLayout>
</Frame>
</StackLayout>
</DataTemplate>
</swipeCardView:SwipeCardView.ItemTemplate>
</swipeCardView:SwipeCardView>
In the C# I created a command but it never enter i the void:
public Command LeftCommand => new Command<string>(LeftSwipe);
void LeftSwipe(string parameter)
{
var variable = parameter; //= breed_Name
DisplayAlert("", variable.ToString(), "ok");
}
I don´t know what I've done wrong because it still swipes
If your LeftCommand is in the ViewModel of your page, you can specify a source just as Jason said.
You can refer to the folloing code:
<swipeCardView:SwipeCardView x:Name="mCardView"
ItemsSource="{Binding CardItems}"
VerticalOptions="FillAndExpand">
<swipeCardView:SwipeCardView.ItemTemplate>
<DataTemplate>
<StackLayout >
<Label Text="{Binding Name}" FontSize="Large" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" BackgroundColor="Beige" />
<StackLayout.GestureRecognizers>
<SwipeGestureRecognizer Direction="Left"
Command="{Binding Path=BindingContext.LeftCommand, Source={x:Reference mCardView}}"
CommandParameter="{Binding .}" >
</SwipeGestureRecognizer>
</StackLayout.GestureRecognizers>
</StackLayout>
</DataTemplate>
</swipeCardView:SwipeCardView.ItemTemplate>
</swipeCardView:SwipeCardView>
Note:
1.mCardView is the x:Name="mCardView" of your SwipeCardView;
2.In your viewModel, you can get the Binded Item as follows:
public Command LeftCommand => new Command(LeftSwipe);
void LeftSwipe(Object parameter)
{
//You can change `Profile ` to your Item Model
Profile variable = parameter as Profile;
System.Diagnostics.Debug.WriteLine("-----------> " + variable.Name +"<---> Id = "+ variable.ProfileId);
}

Xamarin - ImageButton doesnt activate every click

Screen
On the picture above you can see where the ImageButton sometimes activates. When I spam clicking in the blue area the counter sometimes increases. I think there might be another Layer on top of the ImageButton but I dont know how to fix it. Below there is the XAML code. Hopefully somebody can help. Thanks!
<StackLayout>
<Label Text="Discover" TextColor="Black" FontSize="24" FontAttributes="Bold" Margin="15" />
<CarouselView ItemsSource="{Binding plants}" HeightRequest="300" PeekAreaInsets="100">
<CarouselView.ItemTemplate>
<DataTemplate>
<StackLayout>
<Frame HeightRequest="280" WidthRequest="180" BackgroundColor="Wheat" HasShadow="True" Margin="10" Padding="0" HorizontalOptions="CenterAndExpand" CornerRadius="10" >
<Grid>
<StackLayout>
<ImageButton Source="{Binding imgsource}" VerticalOptions="FillAndExpand"
Aspect="AspectFill" Opacity="0.8" Clicked="ImageButton_Clicked"/>
</StackLayout>
<StackLayout Margin="0,10" >
<Image Source="https://icons-for-free.com/iconfiles/png/512/bookmark-131964752402712733.png" HeightRequest="35"
Aspect="AspectFit" HorizontalOptions="EndAndExpand" Margin="5,-15"/>
<Label Text="{Binding name_norm}" TextColor="Black" FontSize="16" FontAttributes="Bold"
Margin="15,-10,0,0" VerticalOptions="EndAndExpand" />
<StackLayout Orientation="Horizontal" Margin="15,-8,0,0" >
<Image Source="https://www.freeiconspng.com/thumbs/info-icon/info-icon-24.png" HeightRequest="15"
Aspect="AspectFit"/>
<Label Text="{Binding name_lat}" TextColor="Black" FontSize="16" FontAttributes="Italic" VerticalOptions="EndAndExpand" Margin="-5,0" />
</StackLayout>
</StackLayout>
</Grid>
</Frame>
</StackLayout>
</DataTemplate>
</CarouselView.ItemTemplate>
</CarouselView>
<Label x:Name="label" Text="0 ImageButton clicks"
FontSize="Large"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand" />
</StackLayout>
Here the C# Code:
namespace PlantBase
{
public partial class MainPage : ContentPage
{
int clickTotal;
public MainPage()
{
InitializeComponent();
}
private void ImageButton_Clicked(object sender, EventArgs e)
{
clickTotal += 1;
label.Text = $"{clickTotal} ImageButton click{(clickTotal == 1 ? "" : "s")}";
}
}
}
Check VisualElement.InputTransparent Property.
false if the element and its children should receive input; true if neither the element nor its children should receive input and should, instead, pass inputs to the elements that are visually behind the current visual element. Default is false.
What you need is to set InputTransparent to true on the text stackLayout .
<StackLayout InputTransparent="True" Margin="0,10" VerticalOptions="EndAndExpand" BackgroundColor="SaddleBrown">
<Label Text="{Binding name_norm}" TextColor="White" FontSize="16" FontAttributes="Bold" Margin="15,-10,0,0" VerticalOptions="EndAndExpand" />
<StackLayout Orientation="Horizontal" Margin="15,-8,0,0" BackgroundColor="Aqua">
<Image Source="https://www.freeiconspng.com/thumbs/info-icon/info-icon-24.png" HeightRequest="15" Aspect="AspectFit" />
<Label Text="{Binding name_lat}" TextColor="White" FontSize="16" FontAttributes="Italic" VerticalOptions="EndAndExpand" Margin="-5,0" />
</StackLayout>
</StackLayout>
Okay I found the Problem. It was that before I put the red Flag on the Top and the text at the bottom in one Stacklayout which expanded from top to bottom. Now that i put them in seperate StackLayouts it works and the ImageButton is free.
Pictures before/after.
old StackLayout
new Stacklayout
The new XAML is:
<CarouselView ItemsSource="{Binding plants}" HeightRequest="300" PeekAreaInsets="100">
<CarouselView.ItemTemplate>
<DataTemplate>
<StackLayout>
<Frame HeightRequest="280" WidthRequest="180" BackgroundColor="Wheat" HasShadow="True" Margin="10" Padding="0" HorizontalOptions="CenterAndExpand" CornerRadius="10" >
<Grid>
<StackLayout>
<ImageButton Source="{Binding imgsource}" VerticalOptions="FillAndExpand"
Aspect="AspectFill" Opacity="0.9" Clicked="ImageButton_Clicked" />
</StackLayout>
<StackLayout VerticalOptions="StartAndExpand" HorizontalOptions="EndAndExpand" BackgroundColor="Aqua">
<ImageButton Source="https://icons-for-free.com/iconfiles/png/512/bookmark-131964752402712733.png" HeightRequest="35"
Aspect="AspectFit" HorizontalOptions="EndAndExpand" Margin="5,0" BackgroundColor="Transparent" Clicked="ImageButton_Clicked_1" />
</StackLayout>
<StackLayout Margin="0,10" VerticalOptions="EndAndExpand" BackgroundColor="SaddleBrown">
<Label Text="{Binding name_norm}" TextColor="White" FontSize="16" FontAttributes="Bold"
Margin="15,-10,0,0" VerticalOptions="EndAndExpand" />
<StackLayout Orientation="Horizontal" Margin="15,-8,0,0" BackgroundColor="Aqua" >
<Image Source="https://www.freeiconspng.com/thumbs/info-icon/info-icon-24.png" HeightRequest="15"
Aspect="AspectFit" />
<Label Text="{Binding name_lat}" TextColor="White" FontSize="16" FontAttributes="Italic" VerticalOptions="EndAndExpand" Margin="-5,0" />
</StackLayout>
</StackLayout>
</Grid>
</Frame>
</StackLayout>
</DataTemplate>
</CarouselView.ItemTemplate>
New Question now. Since at the bottom there is the Text StackLayout, where the Text is I cant press the ImageButton. How can I put the ImageButton as top "layer" so I can also press it while pressing on the text.

Can I use Xamarin Forms ListView with TemplateSelector and ValueConverter inside Template?

I've got a Xamarin ListView that show items based on different DataTemplates, which works fine!
I can use Binding as expected inside the Template definitions.
But when I try to use a ValueConverter inside the Template it never gets called (The converter is working in other places of my Application).
What am I missing here?
I test a demo about ListView with TemplateSelector and ValueConverter inside Template.
I have two DataTemplates, to valiate the value of DateOfBirth.Year, if the Year is over 1980 If the year is over 1980 ,listview will be setted ValidTemplate , if not, listview will be setted InvalidTemplate.
public class PersonDataTemplateSelector : DataTemplateSelector
{
public DataTemplate ValidTemplate { get; set; }
public DataTemplate InvalidTemplate { get; set; }
protected override DataTemplate OnSelectTemplate (object item, BindableObject container)
{
return ((Person)item).DateOfBirth.Year >= 1980 ? ValidTemplate : InvalidTemplate;
}
}
In the location, it will have 0 or 1 value, then I will convert it to the True or False by following code.
public class MyValueConvert : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (int)value != 0;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return (bool)value ? 1 : 0;
}
}
Here is my xaml layout.
<ContentPage.Resources>
<ResourceDictionary>
<local:MyValueConvert x:Key="intToBool" />
<DataTemplate x:Key="validPersonTemplate">
<ViewCell>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.4*" />
<ColumnDefinition Width="0.3*" />
<ColumnDefinition Width="0.3*" />
</Grid.ColumnDefinitions>
<Label Text="{Binding Name}" TextColor="Green" FontAttributes="Bold" />
<Label Grid.Column="1" Text="{Binding DateOfBirth, StringFormat='{0:d}'}" TextColor="Green" />
<Label Grid.Column="2" Text="{Binding Location, Converter={StaticResource intToBool}}" TextColor="Green" HorizontalTextAlignment="End" />
</Grid>
</ViewCell>
</DataTemplate>
<DataTemplate x:Key="invalidPersonTemplate">
<ViewCell>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.4*" />
<ColumnDefinition Width="0.3*" />
<ColumnDefinition Width="0.3*" />
</Grid.ColumnDefinitions>
<Label Text="{Binding Name}" TextColor="Red" FontAttributes="Bold" />
<Label Grid.Column="1" Text="{Binding DateOfBirth, StringFormat='{0:d}'}" TextColor="Red" />
<Label Grid.Column="2" Text="{Binding Location, Converter={StaticResource intToBool}}" TextColor="Red" HorizontalTextAlignment="End" />
</Grid>
</ViewCell>
</DataTemplate>
<local:PersonDataTemplateSelector x:Key="personDataTemplateSelector" ValidTemplate="{StaticResource validPersonTemplate}" InvalidTemplate="{StaticResource invalidPersonTemplate}" />
</ResourceDictionary>
</ContentPage.Resources>
<StackLayout Margin="20">
<Label Text="ListView with a DataTemplateSelector" FontAttributes="Bold" HorizontalOptions="Center" />
<ListView x:Name="listView" Margin="0,20,0,0" ItemTemplate="{StaticResource personDataTemplateSelector}" />
</StackLayout>
Here is running sceenshot.
Here is my demo.
https://github.com/851265601/XFormsData-TempleSelect
So finally I was able to get things working!
My Problem here was that I did implement INotifyPropertyChanged in my ViewModel but not implemented it for the ViewItems itself.
So, even though my ViewItems never change once they where shown in the ListView-Template, it seems to be necessary to implement INotifyPropertyChanged at least for the properties that I want to use with a ValueConverter.
By the way, using a ValueConverter with the same ViewItems without INotifyPropertyChanged BUT without TemplateSelector (i.e. as a ListView-HeaderTemplate), everything works as expected (at least expected by me)

XAML/MVVMx Problems with binding custom Array of object to a Grid

I try to bind an Object with custom Text for testing to my GridView and can't really get the solution.
I already tried to get it rolling with Grid.BindingContext but it won't work.
Can someone help me out here?
<Grid>
<Grid.BindingContext>
<x:Array Type="{x:Type clients:MinRepresentation}<clients:MinRepresentation Id="123456789" PlannedStartTime="01-01-2019" PlannedEndTime="01-12-2019" />
</x:Array>
</Grid.BindingContext>
<StackLayout Orientation="Horizontal" Padding="0,10,0,5" Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="3" BackgroundColor="#CC3F6E3F">
<Image Source="{helpers:ImageResource catkinApp.UI.Images.state_new.png}" Margin="10,0,0,0" />
<Label Text="{Binding ID, StringFormat='ID: [{0}]'}" FontSize="Small" Margin="5,0,10,0" FontAttributes="Bold" TextColor="#FFFFFF"/>
<Label HorizontalTextAlignment="End" Text="(In Bearbeitung)" FontSize="Small" FontAttributes="Bold" TextColor="#FFFFFF"/>
</StackLayout>
</Grid>
According to your description, you want to bind custom object for Grid.BindingContext, you don't need to use Array, you just do like this:
public class model1
{
public string str1 { get; set; }
public string str2 { get; set; }
}
<Grid>
<Grid.BindingContext>
<local:model1 str1="aaaa" str2="bbbb"></local:model1>
</Grid.BindingContext>
<StackLayout Orientation="Vertical">
<Label Text="this is test, please take a look!" />
<Label
Margin="5,0,10,0"
FontAttributes="Bold"
FontSize="Small"
Text="{Binding str1}"
TextColor="#FFFFFF" />
<Label
FontAttributes="Bold"
FontSize="Small"
Text="{Binding str2}"
TextColor="#FFFFFF" />
</StackLayout>
</Grid>
Here is the article from MSDN, you can take a look:
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/data-binding/string-formatting

How i get the control inside dataTemplate in windows phone?

I want change the color os background of the border each listboxitem increase.
<ListBox.ItemTemplate>
<DataTemplate>
<border x:name: border>
<ListBoxItem ItemSource={Binding Example}>
</ListBoxItem>
</border>
Any Ideas?
First check this link, on how to use converters.
Then in your XAML, write your border like this
<Border BorderBrush="{Binding Converter=ColorConverter}">
....
<Border>
Modify your converter code to something like this
public class ColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
//Define some random colors
Color[] colors = { Colors.Blue, Colors.Brown, Colors.Cyan, Colors.Green, Colors.Magenta, Colors.Orange, Colors.Purple, Colors.Yellow, Colors.LightGray };
return colors[(new Random()).Next(8)];
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
}
}
So, this code dynamically returns one of the colors. And there is the chance for getting same color continuously. Btw, I didn't test the above code.
The TypeConverter for "IValueConverter" does not support converting
when i put the border like above causes this error.
here is my complete code
<ItemsControl x:Name="listaAdd" ItemsSource="{Binding sample}" Grid.Row="0" Margin="0,221,0,0" Foreground="White" Background="#FF5B5B5B" >
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Stretch" Grid.Row="1" Width="480" >
<Border x:Name="borda" BorderBrush="{Binding Converter=ColorConverter}" >
<ListBoxItem x:Name="listSelected" Foreground="White" IsSelected="True" VerticalAlignment="Center" FontSize="{StaticResource PhoneFontSizeLarge}" Content="{Binding Nome}" Background="{x:Null}" HorizontalContentAlignment="Left" Height="80" DoubleTap="listSelected_DoubleTap">
</ListBoxItem>
</Border>
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu x:Name="subMenulist">
<Button Grid.Column="1" Content="delete" BorderThickness="0" Margin="0" Background="White" Foreground="#FF1A739D" FontSize="32" HorizontalContentAlignment="Left">
</Button>
<Button Grid.Column="1" Content="compartilhar" Margin="0,0,0,0" x:Name="btnShare" BorderThickness="0" Background="White" Foreground="#FF1A739D" FontSize="32" HorizontalContentAlignment="Left">
</Button>
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>

Resources