Binding MVVM XamarinForms - c#

I have a class where I declare my 'Entry' and put Binding in its Text , I want the bindingContext to be stored in another class that I have.
But something is going wrong, I do not receive the information in the second class
I'm trying to do it like below
BindingContext = new TelaDados();
Label lblNome = new Label()
{
Text = "Digite seu Nome:"
};
Entry enNome = new Entry() { }
enNome.SetBinding(Entry.TextProperty,"Nome");
private void GoPaginaDados()
{
BindingContext = new TelaDados(); ////<---- HERE
DisplayAlert("ok", enNome.Text, "Ok");
Navigation.PushAsync(new TelaDados());
}
here below I try to get the information of the first class
lblNome.SetBinding(Label.TextProperty, "Nome");
the second class would be like this
public string Nome { get; set; }
public string Idade { get; set; }
public string Estado { get; set; }
public TelaDados()
{
Label lblNome = new Label()
{
TextColor = Color.Blue,
BackgroundColor = Color.Green
};
lblNome.SetBinding(Label.TextProperty, "Nome");
BindingContext = this;
}

Related

Adding columns for List<T> inside of a mode class

I created a data model for DataGridView and inside this model there is List<T> property. But DataGridView doesn't display that List<T> property. It displays other properties but it doesn't display List<T> property.
Here is code:
public partial class Form1 : Form
{
List<NotModeli> Notlar;
public Form1()
{
Notlar = new List<NotModeli>()
{
new NotModeli()
{
dersAdi = "Hukuk",
vizeNotu = 78,
araSinav = new List<int>{50},
finalNotu = 98
}
};
InitializeComponent();
veriPaneli.DataSource = Notlar;
}
}
public class NotModeli
{
public string dersAdi { get; set; }
public int vizeNotu { get; set; }
public List<int> araSinav { get; set; }
public int finalNotu { get; set; }
}
If you want to join the elements of the list and display them in one cell, a simple way to go about this would be to create a read-only property that returns the joined elements as string. Your class would look something like this:
public class NotModeli
{
public string dersAdi { get; set; }
public int vizeNotu { get; set; }
public List<int> araSinav { get; set; }
public int finalNotu { get; set; }
[DisplayName("araSinav")]
public string JoinedAraSinav => string.Join(",", araSinav);
}
Now, since we're dealing with numbers, joining them with a comma might not look good. We can use a similar approach to display them in the form of a table (still inside one cell).
First, configure your DataGridView as follows: (you can do that manually using the designer)
veriPaneli.AutoGenerateColumns = false;
var dersAdiCol = new DataGridViewTextBoxColumn()
{
HeaderText = "dersAdi",
DataPropertyName = "dersAdi"
};
var vizeNotuCol = new DataGridViewTextBoxColumn()
{
HeaderText = "vizeNotu",
DataPropertyName = "vizeNotu"
};
var araSinavCol = new DataGridViewTextBoxColumn()
{
HeaderText = "araSinav",
DataPropertyName = "JoinedAraSinav",
Width = 220
};
araSinavCol.DefaultCellStyle.Font =
new Font("Consolas", veriPaneli.Font.Size, veriPaneli.Font.Style);
var finalNotuCol = new DataGridViewTextBoxColumn()
{
HeaderText = "finalNotu",
DataPropertyName = "finalNotu"
};
veriPaneli.Columns.AddRange(dersAdiCol, vizeNotuCol, araSinavCol, finalNotuCol);
Then, change the JoinedAraSinav property to something like the following:
[DisplayName("araSinav")]
public string JoinedAraSinav =>
string.Join(" | ", araSinav.Select(i => i.ToString("00000")));
// ^^^^^
// The number of zeros controls the padding of the displayed numbers.
End result:

How to bind list objects inside Models in Xamarin

I have the following problem, in which I'm trying to Data Bind a List inside a Model to my xaml file. I want to bind the list of IOSensors to the xaml file in some text labels.
Model:
class IOModule
{
public IOModule(string Name, string Type, string Version, string Location, string Desc)
{
this.Name = Name;
this.Type = Type;
this.Version = Version;
this.Serial = Location;
this.Status = Desc;
this.list = new List<IOSensor>();
}
public void addSensorInput(IOSensor sensor)
{
list.Add(sensor);
}
[JsonProperty("Name")]
public String Name { get; set; }
[JsonProperty("Type")]
public String Type { get; set; }
[JsonProperty("Version")]
public String Version { get; set; }
[JsonProperty("Serial")]
public String Serial { get; set; }
[JsonProperty("Status")]
public String Status { get; set; }
public List<IOSensor> list { get; }
public List<String> getIDs
{
get
{
List<string> list1 = new List<string>();
foreach (IOSensor sens in list)
{
list1.Add(sens.ID);
}
return list1;
}
}
}
public class IOSensor
{
public IOSensor(String ID, String Type, String GasComp, String MeasureType, String value)
{
this.ID = ID;
this.IOType = Type;
this.GasComp = GasComp;
this.MeasurementType = MeasureType;
this.Value = value;
}
[JsonProperty("ID")]
public String ID { get; set; }
[JsonProperty("IOType")]
public String IOType { get; set; }
[JsonProperty("GasComp")]
public String GasComp { get; set; }
[JsonProperty("MeasurementType")]
public String MeasurementType { get; set; }
[JsonProperty("Value")]
public String Value { get; set; }
}
ViewModel:
class IoModulesViewModels : BaseViewModel
{
public Item item;
public ObservableCollection<IOModule> modlists;
public IoModulesViewModels(Item item)
{
this.item = item;
this.modlists= new ObservableCollection<IOModule>();
//sendReq();
IOModule mod1 = new IOModule("1", "2", "3", "4", "5");
mod1.addSensorInput(new IOSensor("44", "55", "66", "77", "88"));
mod1.addSensorInput(new IOSensor("444", "545", "646", "747", "848"));
modlists.Add(mod1);
modlists.Add(mod1);
}
}
Xaml:
public partial class IoModulesPage : ContentPage
{
IoModulesViewModels ioModModels;
public IoModulesPage(Item item)
{
InitializeComponent();
BindingContext = this.ioModModels = new IoModulesViewModels(item);
Label header = new Label
{
Text = "ListView",
FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label)),
HorizontalOptions = LayoutOptions.Center
};
ListView lw = new ListView
{
ItemsSource = ioModModels.modlists,
HasUnevenRows = true,
ItemTemplate = new DataTemplate(() =>
{
var grid = new Grid();
Label modHeaderName = new Label();
modHeaderName.SetBinding(Label.TextProperty, "Name");
Label modHeaderType = new Label();
modHeaderType.SetBinding(Label.TextProperty, "Type");
Label modHeaderVersion = new Label();
modHeaderVersion.SetBinding(Label.TextProperty, "Version");
Label modHeaderSerial = new Label();
modHeaderSerial.SetBinding(Label.TextProperty, "Serial");
Label modHeaderStatus = new Label();
modHeaderStatus.SetBinding(Label.TextProperty, "Status");
grid.Children.Add(modHeaderName);
grid.Children.Add(modHeaderType, 1, 0);
grid.Children.Add(modHeaderVersion, 2, 0);
grid.Children.Add(modHeaderSerial, 3, 0);
grid.Children.Add(modHeaderStatus, 4, 0);
ListView lp = new ListView
{
ItemsSource = ioModModels.modlists,
HasUnevenRows = true,
ItemTemplate = new DataTemplate(() =>
{
Label header2 = new Label
{
Text = "ID,Type,GasComp,MeasurementType,Value",
FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Label)),
HorizontalOptions = LayoutOptions.Fill
};
Grid gridIn = new Grid();
Label modID = new Label();
modID.SetBinding(Label.TextProperty, "getIDs");
Label modIOType = new Label();
modIOType.SetBinding(Label.TextProperty, "list.IOType");
Label modGasComp = new Label();
modGasComp.SetBinding(Label.TextProperty, "GasComp");
Label modMeasurementType = new Label();
modMeasurementType.SetBinding(Label.TextProperty, "list[0].MeasurementType");
Label modValue = new Label();
modValue.SetBinding(Label.TextProperty, "list[0].Value");
gridIn.Children.Add(modID);
gridIn.Children.Add(modIOType, 1, 0);
gridIn.Children.Add(modGasComp, 2, 0);
gridIn.Children.Add(modMeasurementType, 3, 0);
gridIn.Children.Add(modValue, 4, 0);
gridIn.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Auto) });
gridIn.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
return new ViewCell
{
View = new StackLayout
{
Padding = new Thickness(0, 10),
Orientation = StackOrientation.Vertical,
Children =
{
header2,
gridIn
}
}
};
})
};
Frame frame = new Frame()
{
BorderColor=Color.Gray,
CornerRadius = 5,
Padding = 8,
Content = new StackLayout
{
Orientation=StackOrientation.Horizontal,
Children =
{
grid,
lp
}
}
};
return new ViewCell
{
View = new StackLayout
{
Padding = new Thickness(0, 10),
Spacing = 2,
Orientation = StackOrientation.Horizontal,
Children =
{
frame
}
}
};
}
)
};
// Accomodate iPhone status bar.
this.Padding = new Thickness(10, Device.OnPlatform(20, 0, 0), 10, 5);
// Build the page.
this.Content = new StackLayout
{
Children =
{
header,
lw
}
};
}
}
As you can see in the xaml file, I ve been trying many apporaches in which i can bind the list of IOSensors, but so far no luck. The Page is loading and showing some results (for example the Syntax with "list[0].property" works but i want it to work for every entry of the list.
Thanks ina dvance
As Jason said that you want to display a nested list of data, so I suggest you can use ListView Group to display data.
I modify your code, and creating one sample, that you can take a look:
Two models:
public class IOModule:List<IOSensor>
{
[JsonProperty("Name")]
public String Name { get; set; }
[JsonProperty("Type")]
public String Type { get; set; }
[JsonProperty("Version")]
public String Version { get; set; }
[JsonProperty("Serial")]
public String Serial { get; set; }
[JsonProperty("Status")]
public String Status { get; set; }
public List<IOSensor> list => this;
}
public class IOSensor
{
[JsonProperty("ID")]
public String ID { get; set; }
[JsonProperty("IOType")]
public String IOType { get; set; }
[JsonProperty("GasComp")]
public String GasComp { get; set; }
[JsonProperty("MeasurementType")]
public String MeasurementType { get; set; }
[JsonProperty("Value")]
public String Value { get; set; }
}
public partial class Page8 : ContentPage
{
public ObservableCollection<IOModule> modlists { get; set; }
public Page8()
{
InitializeComponent();
modlists = new ObservableCollection<IOModule>();
IOModule mod1 = new IOModule()
{
new IOSensor(){ID="IOSensor 1",IOType="",GasComp="",MeasurementType="",Value=""},
new IOSensor(){ID="IOSensor 2",IOType="",GasComp="",MeasurementType="",Value=""}
};
mod1.Name = "IOModule 1";
modlists.Add(mod1);
IOModule mod2 = new IOModule()
{
new IOSensor(){ID="IOSensor 3",IOType="",GasComp="",MeasurementType="",Value=""},
new IOSensor(){ID="IOSensor 4",IOType="",GasComp="",MeasurementType="",Value=""}
};
mod2.Name = "IOModule 2";
modlists.Add(mod2);
IOModule mod3 = new IOModule()
{
new IOSensor(){ID="IOSensor 5",IOType="",GasComp="",MeasurementType="",Value=""},
new IOSensor(){ID="IOSensor 6",IOType="",GasComp="",MeasurementType="",Value=""}
};
mod3.Name = "IOModule 3";
modlists.Add(mod3);
//this.BindingContext = this;
Label header = new Label
{
Text = "ListView",
FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label)),
HorizontalOptions = LayoutOptions.Center
};
ListView lw = new ListView();
lw.ItemsSource = modlists;
lw.IsGroupingEnabled = true;
lw.ItemTemplate = new DataTemplate(() =>
{
var grid = new Grid();
Label modHeaderName = new Label();
modHeaderName.SetBinding(Label.TextProperty, "ID");
Label modHeaderType = new Label();
modHeaderType.SetBinding(Label.TextProperty, "IOType");
Label modHeaderVersion = new Label();
modHeaderVersion.SetBinding(Label.TextProperty, "GasComp");
Label modHeaderSerial = new Label();
modHeaderSerial.SetBinding(Label.TextProperty, "MeasurementType");
Label modHeaderStatus = new Label();
modHeaderStatus.SetBinding(Label.TextProperty, "Value");
grid.Children.Add(modHeaderName);
grid.Children.Add(modHeaderType, 1, 0);
grid.Children.Add(modHeaderVersion, 2, 0);
grid.Children.Add(modHeaderSerial, 3, 0);
grid.Children.Add(modHeaderStatus, 4, 0);
return new ViewCell { View = grid };
});
lw.GroupHeaderTemplate = new DataTemplate(() =>
{
var grid = new Grid();
Label modHeaderName = new Label() {
FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Label)),
FontAttributes = FontAttributes.Bold,
};
modHeaderName.SetBinding(Label.TextProperty, "Name");
//Label modHeaderType = new Label();
//modHeaderType.SetBinding(Label.TextProperty, "Type");
//Label modHeaderVersion = new Label();
//modHeaderVersion.SetBinding(Label.TextProperty, "Version");
//Label modHeaderSerial = new Label();
//modHeaderSerial.SetBinding(Label.TextProperty, "Serial");
//Label modHeaderStatus = new Label();
//modHeaderStatus.SetBinding(Label.TextProperty, "Status");
grid.Children.Add(modHeaderName);
//grid.Children.Add(modHeaderType, 1, 0);
//grid.Children.Add(modHeaderVersion, 2, 0);
//grid.Children.Add(modHeaderSerial, 3, 0);
//grid.Children.Add(modHeaderStatus, 4, 0);
return new ViewCell { View = grid };
});
this.Content = new StackLayout
{
Children =
{
header,
lw
}
};
}
}
This is screenshot;

Carousel View and List View binding not working with Xamarin Forms

I have one big problem with Xamarin Forms - I have to create a carousel view/page with different list in the different pages. This is the code I've written
My main content page is DailyCarouselPage
public class DailyCarouselPage : ContentPage
{
public CarouselViewControl carousel;
public DailyCarouselPage ()
{
ObservableCollection<DailyAppointmentList> collection = new ObservableCollection<DailyAppointmentList>();
collection.Add(new DailyAppointmentList());
collection.Add(new DailyAppointmentList());
StackLayout body = new StackLayout();
carousel = new CarouselViewControl();
carousel.ItemsSource = collection;
carousel.ItemTemplate = new DailyAppointmentListTemplate();
body.Children.Add(carousel);
Content = body;
}
}
Then I have this class that contains the list of the lists that I have to show:
class DailyAppointmentList
{
public ObservableCollection<Appointment> list { get; set; }
public DailyAppointmentList()
{
list = new ObservableCollection<Appointment>();
list = new AppointmentListModel().List; //this list is declared in another class, which isn't important to the problem
}
}
Basic ListView template:
public class DailyAppointmentListTemplate : DataTemplate
{
public DailyAppointmentListTemplate ()
{
StackLayout stack = new StackLayout();
ListView list = new ListView()
{
ItemTemplate = new DataTemplate(typeof(AppointmentCellTemplate))
};
list.SetBinding(ListView.ItemsSourceProperty, "list");
stack.Children.Add(list);
}
}
Template for the cell of the list:
public class AppointmentCellTemplate : ViewCell
{
public AppointmentCellTemplate ()
{
StackLayout stack = new StackLayout();
Label subject = new Label();
subject.SetBinding(Label.TextProperty, "Subject");
Label description = new Label();
description.SetBinding(Label.TextProperty, "Description");
Label date = new Label();
date.SetBinding(Label.TextProperty, "Start");
stack.Children.Add(subject);
stack.Children.Add(description);
stack.Children.Add(date);
View = stack;
}
}
Lastly, my Appointment class:
public class Appointment
{
public Guid? AppointmentId { get; set; }
public DateTime? Start { get; set; }
public DateTime? End { get; set; }
public string Subject { get; set; }
public string Description { get; set; }
public Costumer Costumer { get; set; }
public double? Latitude { get; set; }
public double? Longitude { get; set; }
}
I can't get the list to show in main DailyCarouselPage, no matter what. I tried other methods but didn't work either. Seems like I keep doing some kind of mistake with the bindings, but I can't figure out what I'm doing wrong.
Try to add
Xamarin.Forms.Init();
CarouselViewRenderer.Init();
In your iOS and Android projects to show it.
Then in my test if you want to add ListView in the CarouselViewControl, please just set ItemSource like:
public DailyCarouselPage()
{
ObservableCollection<ListView> collection = new ObservableCollection<ListView>();
ListView myListView = new ListView
{
ItemTemplate = new DataTemplate(typeof(AppointmentCellTemplate)),
ItemsSource = (new DailyAppointmentList()).list
};
collection.Add(myListView);
collection.Add(myListView);
carousel = new CarouselViewControl();
carousel.ItemsSource = collection;
Content = carousel;
}
Moreover, please pay attention to: just set the ContentPage's Content as carousel.

MultiLine in listbox item c#

I'm trying to put data with linebreakes to one item in listbox
how I make a breaklines in this command?
listBox1.Items.Add("");
or other command
thanks
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var product = new Product
{
ProductName = "Some name",
Id = "123X",
Size = "Big",
OutOfStock = "true"
};
var itm = new ListBoxItem {Content = $"Product Name: {product.ProductName} {Environment.NewLine}" +
$"ID: {product.Id} {Environment.NewLine}" +
$"Size: {product.Size} {Environment.NewLine}" +
$"Out of stock {product.OutOfStock}"
};
listBox.Items.Add(itm);
}
}
public class Product
{
public string ProductName { get; set; }
public string Id { get; set; }
public string Size { get; set; }
public string OutOfStock { get; set; }
}

Dynamic Datagrid Columns based on collection

I am having a wrapper for example.
public class Student{
public string Name{get;set}
public int IDNumber{get;set;}
public ObservableCollection<SubjectWrapper> Subjects{get;set;}
}
public class SubjectWrapper{
public string SubjectName{get;set;}
public bool IsSubjectSelected{get;set;}
}
How can I bind this to Datagrid effectively.There could be any number of subject.All students will have all subject column against there name. Please see the following image.Also I want to follow MVVM pattern(less code behind).
XAML
public partial class MainWindow : Window {
public MainWindow()
{
InitializeComponent();
var student = new Student(){ Name = "Ebin"};
student.Subjects.Add(new SubjectWrapper() { SubjectName="subject1",IsSubjectSelected=true });
student.Subjects.Add(new SubjectWrapper(){ SubjectName = "subject2", IsSubjectSelected = false});
var student2 = new Student() { Name = "Ravi" };
student2.Subjects.Add(new SubjectWrapper() { SubjectName = "subject1", IsSubjectSelected = false });
student2.Subjects.Add(new SubjectWrapper() { SubjectName = "subject2", IsSubjectSelected = true });
var list = new List<Student>();
list.Add(student);
list.Add(student2);
//Name column adding
maingrid.Columns.Add(new DataGridTextColumn(){ Header = "name", Binding = new Binding("Name")});
//Subject columns added dynamically
for (int i = 0; i < list[0].Subjects.Count(); i++) {
var col = new DataGridCheckBoxColumn();
col.Header = list[0].Subjects[i].SubjectName;
col.Binding = new Binding("Subjects[" + i.ToString() + "].IsSubjectSelected");
maingrid.Columns.Add(col);
}
maingrid.ItemsSource = list;
}
}
public class Student
{
public string Name { get; set; }
public int IDNumber { get; set; }
public ObservableCollection<SubjectWrapper> Subjects { get; set; }
public Student()
{
Subjects = new ObservableCollection<WpfApplication1.SubjectWrapper>();
}
}
public class SubjectWrapper {
public string SubjectName { get; set; }
public bool IsSubjectSelected { get; set; }
}

Categories

Resources