In my content page (XAML), let's say I have this:
<StackLayout>
<Entry x:Name="courseScore" Placeholder="Course Score" Keyboard="Numeric" />
<Entry x:Name="courseGrade" Placeholder="Course Grade" Keyboard="Text" IsReadOnly="True" />
</StackLayout>
How do I create event handler (example, onKeyup) for courseScore? I want to auto populate course grade based on course score from code behind?
Solution provided by Lucas:
<?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:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Xamarin_SQLite.AppFunctions"
mc:Ignorable="d"
x:Class="Xamarin_SQLite.Views.StudentCourseResult_Add">
<ContentPage.Resources>
<ResourceDictionary>
<local:ScoreConverter x:Key="ScoreConverter" />
</ResourceDictionary>
</ContentPage.Resources>
<ContentPage.Content>
<StackLayout>
<Picker Title="Select a course" x:Name="courseName">
<Picker.Items>
<x:String>Web Design</x:String>
<x:String>Database Design</x:String>
<x:String>Web Programming</x:String>
</Picker.Items>
</Picker>
<Entry x:Name="courseScore" Placeholder="Course Score" Keyboard="Numeric" />
<Entry x:Name="courseGrade" Placeholder="Course Grade" Keyboard="Text" IsReadOnly="True" />
<Button x:Name="btnAdd" Clicked="btnAdd_Clicked" Text="Add"/>
</StackLayout>
</ContentPage.Content>
</ContentPage>
You can implement it by using Converter .
using System;
using System.Globalization;
using Xamarin.Forms;
namespace xxxx
{
public class ScoreConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if(value!=null&& value.ToString().Length!=0)
{
int score = int.Parse(value.ToString());
if (score < 60)
{
return "E";
}
else if (score >= 60 && score < 70)
{
return "D";
}
else if (score >= 70 && score < 80)
{
return "C";
}
else if (score >= 80 && score < 90)
{
return "B";
}
else
{
return "A";
}
}
return "";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return "";
}
}
}
in xaml
<ContentPage.Resources>
<ResourceDictionary>
<local:ScoreConverter x:Key="ScoreConverter" />
</ResourceDictionary>
</ContentPage.Resources>
<StackLayout VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
<Entry x:Name="courseScore" Placeholder="Course Score" Keyboard="Numeric" />
<Entry x:Name="courseGrade" Placeholder="Course Grade" Keyboard="Text" IsReadOnly="True" Text="{Binding Source={x:Reference courseScore}, Path=Text,Converter={StaticResource ScoreConverter} ,Mode=OneWay}"/>
</StackLayout>
Related
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)
I have a label with black text color inside a frame with white background color, the thing is, I want to assign the background color and text color from the viewmodel, I have created the converter, and did the bindings, but for some reason it isn't working
this is my view code:
?xml version="1.0" encoding="UTF-8"?>
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ComanderoMovil.Views.PlatillosView"
xmlns:ios="clr -namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core"
ios:Page.UseSafeArea="true"
xmlns:behaviorsPack="clr- namespace:Xamarin.Forms.BehaviorsPack;assembly=Xamarin.Forms.Behaviors Pack"
xmlns:converterPack="clr-namespace:ComanderoMovil.Converters">
<ContentPage.Resources>
<ResourceDictionary>
<converterPack:ColorConverter x:Key="ColorConverter"/>
</ResourceDictionary>
</ContentPage.Resources>
<ContentPage.Content>
<StackLayout>
<SearchBar> </SearchBar>
<CollectionView ItemsSource="{Binding Grupos}"
HeightRequest="50"
ItemsLayout="HorizontalList"
SelectionMode="Single"
SelectionChangedCommand="{Binding
SelectedGrupoCommand, Mode=TwoWay}">
<CollectionView.ItemTemplate>
<DataTemplate>
<ContentView Padding="2">
<Frame BorderColor="Black"
HasShadow="False"
Padding="2"
BackgroundColor="{Binding
ButtonBackColor, Converter={StaticResource ColorConverter}}">
<StackLayout>
<Label Margin="10"
Text="{Binding nombre}"
TextColor="{Binding
TextColor, Converter = {StaticResource ColorConverter}}"
VerticalTextAlignment="Center"
HorizontalTextAlignment="Center"
FontSize="Small"
VerticalOptions="CenterAndExpand"></Label>
</StackLayout>
</Frame>
</ContentView>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</ContentPage.Content>
</ContentPage>
Here is my ViewModel:
public class PlatillosViewModel : INotifyPropertyChanged
{
private INavigation Navigation;
private ObservableCollection<PlatilloModel> _platillos;
private string _textColor;
private string _backColor;
public event PropertyChangedEventHandler PropertyChanged;
public ObservableCollection<GrupoModel> Grupos { get; set; }
public ObservableCollection<PlatilloModel> Platillos
{
get => _platillos;
set
{
_platillos = value;
OnPropertyChanged();
}
}
public string TextColor
{
get => _textColor;
set
{
_textColor = value;
OnPropertyChanged();
}
}
public string ButtonBackColor
{
get => _backColor;
set
{
_backColor = value;
OnPropertyChanged();
}
}
public PlatillosViewModel(INavigation navigation)
{
Navigation = navigation;
TextColor = "Black";
ButtonBackColor = "White";
PlatillosRepository repository = new PlatillosRepository();
Platillos = repository.GetAll();
GrupoRepository grupoRepository = new GrupoRepository();
Grupos = grupoRepository.GetAll();
}
public ICommand SelectedPlatilloCommand => new Command<PlatilloModel>(async platillo =>
{
await Navigation.PushAsync(new PlatilloView());
});
public ICommand SelectedGrupoCommand => new Command<GrupoModel>(async grupo =>
{
ButtonBackColor = "Black";
TextColor = "White";
PlatillosRepository platillosRepository = new PlatillosRepository();
Platillos = platillosRepository.GetFilteredByGroup(grupo);
});
protected virtual void OnPropertyChanged([CallerMemberName] string property = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
}
}
and Here is my converter:
public class ColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var valor = value.ToString();
switch(valor)
{
case "White":
return Color.White;
case "Black":
return Color.Black;
default:
return Color.Red;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
Your issue is not with the ValueConverter but with your Bindings.
<CollectionView ItemsSource="{Binding Grupos}"
HeightRequest="50"
ItemsLayout="HorizontalList"
SelectionMode="Single"
SelectionChangedCommand="{Binding SelectedGrupoCommand, Mode=TwoWay}">
<CollectionView.ItemTemplate>
<DataTemplate>
<ContentView Padding="2">
<Frame BorderColor="Black"
HasShadow="False"
Padding="2"
BackgroundColor="{Binding ButtonBackColor, Converter={StaticResource ColorConverter}}">
<StackLayout>
<Label Margin="10"
Text="{Binding nombre}"
TextColor="{Binding TextColor, Converter = {StaticResource ColorConverter}}"
VerticalTextAlignment="Center"
HorizontalTextAlignment="Center"
FontSize="Small"
VerticalOptions="CenterAndExpand">
</Label>
</StackLayout>
</Frame>
</ContentView>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
You are using a CollectionView and when you set the ItemSource
<CollectionView ItemsSource="{Binding Grupos}"
All the bindings you do inside will assume this as the BindingContext.
<Label Margin="10"
Text="{Binding nombre}"
TextColor="{Binding TextColor, Converter = {StaticResource ColorConverter}}"
VerticalTextAlignment="Center"
HorizontalTextAlignment="Center"
FontSize="Small"
VerticalOptions="CenterAndExpand" />
The same way the nombre property you are binding to the Label Text Property, is part of the GroupModel class, that way the TextColor and ButtonBackColor properties are expected to be part of the same class you did bind as the ItemSource.
If you want to make it work: either add these two properties (TextColor and ButtonBackColor) to the GroupModel class or change the binding so that these two properties are accessed from the parent Binding.
The first one will give you more flexibility but at the same time might add repeated code (if all the items will share the same color for example).
The second option can be accomplished this way:
Add a name to the CollectionView
<CollectionView ItemsSource="{Binding Grupos}"
HeightRequest="50"
x:Name="GruposList"
....
Then we are gonna change a bit the binding of those items that are not part of your GrupoModel but are part of the ViewModel
<DataTemplate>
<ContentView Padding="2">
<Frame BorderColor="Black"
HasShadow="False"
Padding="2"
BackgroundColor="{Binding BindingContext.ButtonBackColor,
Source={x:Reference GruposList},
Converter={StaticResource ColorConverter}}">
<StackLayout>
<Label Margin="10"
Text="{Binding nombre}"
TextColor="{Binding BindingContext.TextColor,
Source={x:Reference GruposList},
Converter={StaticResource ColorConverter}}"
VerticalTextAlignment="Center"
HorizontalTextAlignment="Center"
FontSize="Small"
VerticalOptions="CenterAndExpand">
</Label>
</StackLayout>
</Frame>
</ContentView>
</DataTemplate>
As you can see we are now accessing them through the CollectionView Binding, we do this when we specify the Source and use a Reference. More about bindings here
Hope this helps.-
Side Note:
In your converter watch for nulls.
var valor = value.ToString();
The above can make your application crash if value is null.
Use this instead:
var valor = value?.ToString();
I'm learning Xamarin Data Binding and learning the below code:
<?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:DataBinding"
x:Class="DataBinding.MainPage">
<StackLayout>
<Label x:Name="label" Text="twisting" FontSize="70" HorizontalOptions="Center" VerticalOptions="CenterAndExpand"
BindingContext="{x:Reference Name=slider}"
Rotation="{Binding Path=Value}">
</Label>
<Slider x:Name="slider" BackgroundColor="Yellow" Maximum="360" VerticalOptions="CenterAndExpand">
</Slider>
</StackLayout>
</ContentPage>
I want to double the twisting speed so I modify the code:
<Label x:Name="label" Text="twisting" FontSize="70"
HorizontalOptions="Center" VerticalOptions="CenterAndExpand"
BindingContext="{x:Reference Name=slider}"
Rotation="{Binding Path=Value*2}">
</Label>
But it doesn't work at all. I know the below solution works but I want a solution relating to the above:
<Slider x:Name="slider" BackgroundColor="Yellow" Maximum="720" VerticalOptions="CenterAndExpand">
</Slider>
How to do it?
UPDATE1
I customize a converter as the below code:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Xamarin.Forms;
namespace DataBinding
{
public class MyValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var speed = value as int?;
return speed * 2;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
}
and modify the xaml as the below:
<?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:DataBinding"
x:Class="DataBinding.MainPage">
<StackLayout>
<Label x:Name="label" Text="twisting" FontSize="70" HorizontalOptions="Center" VerticalOptions="CenterAndExpand"
BindingContext="{x:Reference Name=slider}"
Rotation="{Binding Path, Converter={StaticResource myCo
nverter}}">
</Label>
<Slider x:Name="slider" BackgroundColor="Yellow" Maximum="360" VerticalOptions="CenterAndExpand">
</Slider>
</StackLayout>
<ContentPage.Resources>
<ResourceDictionary>
<local:MyValueConverter x:Key="myConverter"></local:MyValueConverter>
</ResourceDictionary>
</ContentPage.Resources>
</ContentPage>
But my converter doesn't work properly and what is more, I made a breakpoint and found that the Convert function even not getting triggered.
UPDATE2
I found out the reason, the label in XAML should be the below:
<Label x:Name="label" Text="twisting" FontSize="70" HorizontalOptions="Center" VerticalOptions="CenterAndExpand"
BindingContext="{x:Reference Name=slider}"
Rotation="{Binding Path=Value, Converter={StaticResource myConverter}}">
</Label>
and the type of value inside the Convert function is double instead of string:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var tmp = (Double)value*2;
return tmp;
}
Then it works.
Here is the method that I have come up with so far. However it seems like not such a clean solution.
Does anyone have any suggestions how I could come up with a better solution for doing this?
<?xml version="1.0" encoding="utf-8"?>
<StackLayout xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:Japanese;assembly=Japanese"
x:Class="Japanese.Templates.HeaderTemplate"
x:Name="this" HorizontalOptions="FillAndExpand" Orientation="Vertical" Spacing="0" Margin="0">
<StackLayout IsVisible="{Binding HeaderType, Converter={StaticResource HeaderType1BoolConverter}, Source={x:Reference this} }" >
<!-- code -->
</StackLayout>
<StackLayout IsVisible="{Binding HeaderType, Converter={StaticResource HeaderType2BoolConverter}, Source={x:Reference this} }" >
<!-- code -->
</StackLayout>
</StackLayout>
In my bank end CS:
using System;
using System.Collections.Generic;
using Xamarin.Forms;
namespace Japanese.Templates
{
public partial class HeaderTemplate : StackLayout
{
public HeaderTemplate()
{
InitializeComponent();
}
public static readonly BindableProperty HeaderTypeProperty =
BindableProperty.Create(
nameof(HeaderType),
typeof(string),
typeof(DataViewCellTemplate),
default(string));
public string HeaderType
{
get { return (string)GetValue(HeaderTypeProperty); }
set { SetValue(HeaderTypeProperty, value); }
}
}
}
Converter Code:
public class HeaderType1BoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return object.Equals(value, "1");
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
public class HeaderType2BoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return object.Equals(value, "2");
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
In the calling code:
<template:HeaderTemplate Header="Application" HeaderType="1" />
Using triggers is an option.
For e.g.: You can add property-triggers to check the value on HeaderType and accordingly update the Content (or layout) in your custom control HeaderView.
Please note in this case we are extending from ContentView not StackLayout on the assumption that only one layout/control is visible at a time.
XAML
<ContentView
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:SampleApp"
x:Class="SampleApp.HeaderView">
<ContentView.Triggers>
<!-- if header type is 1, use header1 layout -->
<Trigger TargetType="local:HeaderView" Property="HeaderType" Value="1">
<Setter Property="Content">
<Setter.Value>
<Label Text="Header1" />
</Setter.Value>
</Setter>
</Trigger>
<!-- if header type is 2, use header2 layout -->
<Trigger TargetType="local:HeaderView" Property="HeaderType" Value="2">
<Setter Property="Content">
<Setter.Value>
<StackLayout>
<Label Text="Header2" />
<BoxView HeightRequest="1" BackgroundColor="Gray" />
</StackLayout>
</Setter.Value>
</Setter>
</Trigger>
<!-- you can add more layouts here if you need -->
</ContentView.Triggers>
<!-- add default content that can be displayed in case of no match -->
<StackLayout>
<Label Text="DefaultHeader" />
<BoxView HeightRequest="1" BackgroundColor="Gray" />
</StackLayout>
</ContentView>
Code-behind
public partial class HeaderView : ContentView
{
public HeaderView()
{
InitializeComponent();
}
public static readonly BindableProperty HeaderTypeProperty =
BindableProperty.Create(
nameof(HeaderType), typeof(string), typeof(HeaderView),
defaultValue: default(string));
public string HeaderType
{
get { return (string)GetValue(HeaderTypeProperty); }
set { SetValue(HeaderTypeProperty, value); }
}
}
Usage
<local:HeaderView HeaderType="1" />
I believe that what you are looking is a ControlTemplate here is an implementation.
App.xaml
<Application xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="SimpleTheme.App">
<Application.Resources>
<ResourceDictionary>
<ControlTemplate x:Key="Header1Template">
<StackLayout>
<!-- code -->
</StackLayout>
</ControlTemplate>
<ControlTemplate x:Key="Header2Template">
<StackLayout>
<!-- code -->
</StackLayout>
</ControlTemplate>
</ResourceDictionary>
</Application.Resources>
</Application>
Usage (This will make header1 your default, you can pick any of the both)
<ContentView x:Name="contentView" ControlTemplate="{StaticResource Header1Template}">
Now there are many ways to change the header, either by defining as the default code above or with an action which can be a button click like the example given on the link or with a propertyChange event, if you want to depend on a property to choose the header like:
public int HeaderNumber { get; set; }
protected override void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
base.OnPropertyChanged(propertyName);
if (propertyName == "HeaderNumber")
{
contentView.ControlTemplate = (HeaderNumber == 1) ? Header1Template : Header2Template;
}
}
Note that i never implemented a ControlTemplate but i think this solves your problem.
I’m trying to serialize class but I can’t do it.
I have a class below:
public class DadosTitulo
{
public string nome { get; set; }
public string numeroCpfCnpj { get; set; }
public string logradouro { get; set; }
public string numero { get; set; }
public string complemento { get; set; }
public string bairro { get; set; }
public string cep { get; set; }
public string municipio { get; set; }
public string uf { get; set; }
public double valor { get; set; }
public string numeroDocumento { get; set; }
public string dataVencimento { get; set; }
public string celularDestino { get; set; }
public bool registroProducao { get; set; }
}
And in my MainPage.xaml.cs I have:
private async void btnAdicionar_Clicked(object sender, EventArgs e)
{
var retorno = "";
var titulo = new DadosTitulo
{
nome = txtNome.Text,
numeroCpfCnpj = txtNumeroCpfCnpj.Text,
logradouro = txtLogradouro.Text,
numero = txtNumero.Text,
complemento = txtComplemento.Text,
bairro = txtBairro.Text,
cep = txtCep.Text,
municipio = txtMunicipio.Text,
uf = txtUF.Text,
valor = Convert.ToDouble(txtValor.Text),
numeroDocumento = txtNumeroDocumento.Text,
dataVencimento = DataVencimento.Date.ToString("dd/MM/yyyy"),
celularDestino = txtDddCelularDestino.Text + txtNumCelularDestino.Text,
registroProducao = RegistraProducao
};
var registroService = new RegistroBoletoService();
retorno = registroService.RegistrarBoleto(titulo);
await DisplayAlert("Json", retorno, "OK");
}
Property Values from MainPage.xaml:
<?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:AppRegistraBoletoXF"
x:Class="AppRegistraBoletoXF.MainPage">
<StackLayout Orientation="Vertical">
<StackLayout>
<Label Text="Registra Boleto" TextColor="Indigo" FontSize="Medium" />
</StackLayout>
<StackLayout>
<Label Text="Informe os dados do Título:" TextColor="Black" FontSize="Small" />
</StackLayout>
<StackLayout>
<Entry x:Name="txtNome" Placeholder="Nome" HorizontalOptions="Start"
VerticalOptions="StartAndExpand" HeightRequest="35" WidthRequest="300" FontSize="Small"/>
<Entry x:Name="txtNumeroCpfCnpj" Placeholder="CPF/CNPJ" HorizontalOptions="Start"
VerticalOptions="StartAndExpand" HeightRequest="35" WidthRequest="300" FontSize="Small" />
<StackLayout Orientation="Horizontal">
<Entry x:Name="txtLogradouro" Placeholder="Logradouro" HorizontalOptions="StartAndExpand" VerticalOptions="Start"
HeightRequest="35" WidthRequest="160" FontSize="Small" />
<Entry x:Name="txtNumero" Placeholder="Número" HorizontalOptions="StartAndExpand" VerticalOptions="Start"
HeightRequest="35" WidthRequest="50" FontSize="Small" />
<Entry x:Name="txtComplemento" Placeholder="Complemento" HorizontalOptions="StartAndExpand" VerticalOptions="Start"
HeightRequest="35" WidthRequest="90" FontSize="Small" />
</StackLayout>
<StackLayout Orientation="Horizontal">
<Entry x:Name="txtBairro" Placeholder="Bairro" HorizontalOptions="StartAndExpand" VerticalOptions="Start"
HeightRequest="35" WidthRequest="180" FontSize="Small" />
<Entry x:Name="txtCep" Placeholder="CEP" HorizontalOptions="StartAndExpand" VerticalOptions="Start"
HeightRequest="35" WidthRequest="120" FontSize="Small" />
</StackLayout>
<StackLayout Orientation="Horizontal">
<Entry x:Name="txtMunicipio" Placeholder="Município" HorizontalOptions="StartAndExpand" VerticalOptions="Start"
HeightRequest="35" WidthRequest="250" FontSize="Small" />
<Entry x:Name="txtUF" Placeholder="UF" HorizontalOptions="StartAndExpand" VerticalOptions="Start"
HeightRequest="35" WidthRequest="50" FontSize="Small" />
</StackLayout>
<StackLayout Orientation="Horizontal">
<Entry x:Name="txtDddCelularDestino" Placeholder="DDD" HorizontalOptions="StartAndExpand" VerticalOptions="Start"
HeightRequest="35" WidthRequest="50" FontSize="Small" />
<Entry x:Name="txtNumCelularDestino" Placeholder="Celular Destino" HorizontalOptions="StartAndExpand" VerticalOptions="Start"
HeightRequest="35" WidthRequest="250" FontSize="Small" />
</StackLayout>
<Entry x:Name="txtNumeroDocumento" Placeholder="Número do Título" HorizontalOptions="Start"
VerticalOptions="StartAndExpand" HeightRequest="35" WidthRequest="300" FontSize="Small"/>
<Entry x:Name="txtValor" Placeholder="Valor do Título" HorizontalOptions="Start"
VerticalOptions="StartAndExpand" HeightRequest="35" WidthRequest="300" FontSize="Small"/>
<StackLayout Orientation="Horizontal">
<Label Text="Registro em Produção: " TextColor="Black" FontSize="Small" HorizontalOptions="Start"
VerticalOptions="StartAndExpand" />
<DatePicker DateSelected="DataSelecionada" HorizontalOptions="Start" VerticalOptions="StartAndExpand">
<DatePicker.Format>dd/MM/yyyy</DatePicker.Format>
</DatePicker>
</StackLayout>
<StackLayout Orientation="Horizontal">
<Label Text="Registro em Produção: " TextColor="Black" FontSize="Small" HorizontalOptions="Center"
VerticalOptions="StartAndExpand" />
<Switch IsToggled="False" Toggled="RegistrarProducao" HorizontalOptions="Center"
VerticalOptions="StartAndExpand" />
</StackLayout>
<Button HorizontalOptions="FillAndExpand" VerticalOptions="StartAndExpand" HeightRequest="40" Text="Registrar Título"
Clicked="btnAdicionar_Clicked" FontSize="Small"/>
</StackLayout>
</StackLayout>
</ContentPage>
In RegistroBoletoService:
public string RegistrarBoleto(DadosTitulo dadosTitulo)
{
var data = JsonConvert.SerializeObject(dadosTitulo);
return data;
}
data allways return “{}”:
I have made a test calling RegistroBoletoService from Console Project, in the same Solution, and the result was as expected: data contains json
The interesting point that I noticed: when I have instantiated the class in MainPage.xaml.cs the behavior was diferent from Console Project, with Non-Public Members in the class:
Console Instantiate:
I think that this is the problem, anyone have an idea what is it happening ? Why when I have instantiated the class in the MainPage I get different behavior from the Console ?
Thanks a lot and sorry my English.
PS.: Project in .NET Standard; I’m not using MVVM in this case; I tried testing with the linker SDK Assemblies Only and None.