Im learning about data binding on windows phone , so far i've been able to bind single objects to the visual side of the app, but now im trying to understand how i can get visual elements to be created according to the number of objects i have on a list
I have a class for a person
public class Person
{
public Person() { }
public string name { get; set; }
public string fotoPath { get; set; }
}
and i have a class for the collection of persons
public class PersonCollection
{
public PersonCollection() { }
public List<Person> personGroup { get; set; }
}
Then i have my page's code behind, where i generate my list of persons
public partial class TestPage : PhoneApplicationPage
{
public TestPage()
{
InitializeComponent();
Loaded += TestPage_Loaded;
}
void TestPage_Loaded(object sender, RoutedEventArgs e)
{
PersonCollection lista = new PersonCollection();
lista.personGroup.Add(new Person(){name = "Mr.T", fotoPath = "/images/foto1.jpg"});
lista.personGroup.Add(new Person(){name = "John", fotoPath = "/images/foto2.jpg"});
}
}
on my page i want to have a grid that shows on each cell a photo and the name of the person, for each person on my list(2 persons per line). As far as i understood i'll be needing to use DataTemplate, but for now my efforts have failed.
can anyone give me some pointers?
Here's how you could present 2 people per line. First, put the source collection into groups of 2:
List<Tuple<Person, Person>> groupedItems = lista.personGroup
.GroupBy(item => lista.personGroup.IndexOf(item) / 2)
.Select(grp => new Tuple<Person, Person>(grp.First(), grp.Skip(1).FirstOrDefault()))
.ToList();
items.ItemsSource = groupedItems;
Now use a DataTemplate that presents "Item1" and "Item2" in left and right columns:
<ItemsControl x:Name="items">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.Resources>
<DataTemplate x:Key="ColumnTemplate">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding name}" Width="150" />
<Image Source="{Binding fotoPath}" />
</StackPanel>
</DataTemplate>
</Grid.Resources>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<ContentControl Content="{Binding Item1}"
ContentTemplate="{StaticResource ColumnTemplate}" />
<ContentControl Grid.Column="1"
Content="{Binding Item2}"
ContentTemplate="{StaticResource ColumnTemplate}" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Related
OK, I think similar questions have already been asked, but I can't get this to work. I have a View with an ItemsControl like this:
<Grid Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Label Content="Model Health Report:" Margin="10,10,10,0" Height="26" VerticalAlignment="Top" FontWeight="Bold"/>
<ItemsControl Grid.Row="1"
ItemsSource="{Binding HealthReports, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type hr:HealthReportSummaryControl}"/>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
That has a view model behind it like this:
public class CommunicatorViewModel : ViewModelBase
{
public ObservableCollection<HealthReportSummaryViewModel> HealthReports { get; set; }
public CommunicatorModel Model { get; set; }
public CommunicatorViewModel(HealthReportData data)
{
Model = new CommunicatorModel();
HealthReports = new ObservableCollection<HealthReportSummaryViewModel>
{
new HealthReportSummaryViewModel {Title = "View1", Description = "Some desc."},
new HealthReportSummaryViewModel {Title = "View2", Description = "Some desc."}
};
}
}
As you can see I am binding it to an ObservableCollection of HealthReportSummaryViewModel objects. These are populated in the constructor. I checked the objects at runtime, they are correct.
The actual control looks like this:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50"/>
<ColumnDefinition Width="2"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Ellipse Grid.Column="0"
Fill="{Binding FillColor}"
Margin="2"/>
<Rectangle Grid.Column="1"
Fill="DarkGray"
Margin="0,2"/>
<Label Content="{Binding Title}"
Grid.Column="2"
Margin="5,0,10,0"
VerticalAlignment="Top"/>
<TextBlock Grid.Column="2"
Margin="5,10,10,0"
TextWrapping="Wrap"
Text="{Binding Description}"/>
</Grid>
With a view model:
public class HealthReportSummaryViewModel : ViewModelBase
{
private System.Windows.Media.Color _fillColor;
public System.Windows.Media.Color FillColor {
get { return _fillColor; }
set { _fillColor = value; RaisePropertyChanged(() => FillColor); }
}
private string _title;
public string Title
{
get { return _title; }
set { _title = value; RaisePropertyChanged(() => Title); }
}
private string _description;
public string Description
{
get { return _description; }
set { _description = value; RaisePropertyChanged(() => Description); }
}
}
I am getting no exceptions, but my window has only empty items. There is a rectangle in the user control that is not dependent on data binding so perhaps this is an issue with the size of the content? I can't figure this out. It's all blank. Do I need to somehow set the size for each ItemsControl item, or will they just adjust to size of the grid they are placed in? What am i missing here? All help will be appreciated.
Your DataTemplate definition is wrong:
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type hr:HealthReportSummaryControl}"/>
</ItemsControl.ItemTemplate>
This defines an empty data template for the items of the HealthReportSummaryControl type.
Instead, you should define it like that:
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type hr:HealthReportSummaryViewModel}">
<hr:HealthReportSummaryControl/>
</DataTemplate>
</ItemsControl.ItemTemplate>
This defines a template for the HealthReportSummaryViewModel items.
I'm new to Xamarin and C#, so forgive me if my code is crap.
So essentially I'm trying to create a simple page that displays a list of course names, and allows a button to insert or remove items from the list within the view.
As of now the program builds and runs but the view does not display the contents of the list. Any help would be greatly appreciated. Thanks!
Here's the view:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="65" />
<RowDefinition Height="*"/>
<RowDefinition Height="50" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Frame OutlineColor="Black" Grid.Row="0" Grid.ColumnSpan="2">
<Label Text= "My Courses" FontSize="20" TextColor="Black" HorizontalTextAlignment="Center"/>
</Frame>
<Frame OutlineColor="Black" Grid.Row="1" Grid.ColumnSpan="2">
<ListView x:Name="CourseList" ItemsSource="{Binding GetCourseList}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="50" />
</Grid.ColumnDefinitions>
<Label FontSize="14" Text="{Binding Name}" TextColor="Black" Grid.Row="0" Grid.Column="0"/>
<Button FontSize="14" Text="X" TextColor="Black" Grid.Row="0" Grid.Column="1"/>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Frame>
<Button Text="+" FontSize="20" TextColor="Green" BackgroundColor="Silver"
HorizontalOptions="Fill" VerticalOptions="Center"
Grid.Row="2" Grid.ColumnSpan="2"
/>
</Grid>
Here's the View.cs code:
public partial class MainPage : ContentPage
{
MainPageViewModel vm;
public MainPage()
{
vm = new MainPageViewModel();
vm.AddCourse();
BindingContext = vm;
InitializeComponent();
}
Here's the View Model:
class MainPageViewModel
{
public string Name { get; set; }
public List<Course> Courses;
public MainPageViewModel()
{
Courses = new List<Course>();
}
public List<Course> GetCourseList()
{
return Courses;
}
public void AddCourse()
{
Course NewCourse = new Course();
NewCourse.Name = "New Course Added";
Courses.Add(NewCourse);
}
}
Finally, Here's my Model:
public class Course
{
public string Name { get; set; }
}
So I have been able to display a list using this code but I do not believe this will allow me to add or delete from the list and update the view via button click (Correct me if I'm wrong).
public List<Course> Courses{
get{
return new List<Course>(){
new Course(){Name = "Added a course"}
};
}
I think I just found my error and solution.
public List<Course> Courses{
get{
return new List<Course>(){
new Course(){Name = "Added a course"}
};
}
Because Courses is "read only" and now being bound to the view I created a member variable List VMCourse to hold the actually list of objects and am using Courses to be bounded to and read into the view.
It appears to work, but I still need to test it with button features for adding and deleting from the list. Does this look like a decent solution to you guys?
Thanks in advance!
class MainPageViewModel
{
public string Name { get; set; }
public List<Course> VMCourse;
//This is now bound to the view's listview
public List<Course> Courses {
get
{
return VMCourse;
}
}
public MainPageViewModel()
{
VMCourse = new List<Course>();
}
public void AddCourse()
{
Course NewCourse = new Course();
NewCourse.Name = "New Course Added";
VMCourse.Add(NewCourse);
}
You cannot bind a list to a method. You should use binding with properties. So to fix this you only need to change
public List<Course> GetCourseList()
{
return Courses;
}
To
public List<Course> GetCourseList
{
get { return Courses; }
}
But, as it's mentioned in the comments not any property is suitable to be used with binding unless you know what you are doing so search about binding.
I need to dig into a nested observable collection in UWP, which consists another observable collection inside it, and then bind it to my XAML.
How could I do it?
Allen Rufolo's Solution works. But Here is another way of approaching this.
x:Bind is newly implemented and available for UWP. My Answer is based on x:Bind
Sample Classes
public class MainItems
{
public string ItemName { get; set; }
public ObservableCollection<SubItems> SubItemsList { get; set; }
}
public class SubItems
{
public string SubItemName { get; set; }
}
Sample Data
ObservableCollection<MainItems> _data = new ObservableCollection<MainItems>();
for (int i = 1; i <= 5; i++)
{
MainItems _mainItems = new MainItems();
_mainItems.ItemName = "Main" + i.ToString();
_mainItems.SubItemsList = new ObservableCollection<SubItems>();
for (int j = 1; j <= 3; j++)
{
SubItems _subItems = new SubItems()
{
SubItemName = "SubItem" + i.ToString()
};
_mainItems.SubItemsList.Add(_subItems);
}
_data.Add(_mainItems);
}
My XAML
<ListView x:Name="MyMainList">
<ListView.ItemTemplate>
<DataTemplate x:DataType="local:MainItems">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock Text="{x:Bind ItemName}" />
<ListView ItemsSource="{x:Bind SubItemsList}" Grid.Row="1">
<ListView.ItemTemplate>
<DataTemplate x:DataType="local:SubItems">
<TextBlock Foreground="Red" Text="{x:Bind SubItemName}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
x:Bind gives you an easy way to Bind your Nested Observable Collection
Output
A code example of your observable collections would help but you could do something like this...
public class MyViewModel
{
public ObservableCollection<MyObject> MyObjectCollection { get; set;}
}
public class MyObject
{
public string ObjectName {get; set;}
public ObservableCollection<AnotherObject> AnotherObjectCollection { get; set; }
}
And in your XAML you can bind to these collection similar to this
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ListView x:Name="ListView1" Grid.Column="0"
ItemsSource="{Binding MyObjectCollection}">
<ListView.ItemTemplate>
<Datatemplate>
<TextBlock Text="{Binding ObjectName}"/>
</Datatemplate
</ListView.ItemTemplate>
</ListView>
<Grid Grid.Column=1 DataContext="{Binding ElementName=ListView1, Path=SelectedItem}">
<ListView ItemsSource="{Binding AnotherObjectCollection}"/>
</Grid>
</Grid>
In this example, the DataContext of the second Grid is bound to the selected item in ListView1.
I am not sure that I get what do you need, but I guess that it could be the same as for WPF.
Check out questions and answers for the next questions:
Binding nested ItemsControls to nested collections
Nested ObservableCollection data binding in WPF
WPF Binding on Nested ItemControls with Sub Collection
Databinding for nested collections in XAML (WPF and Silverlight)
I develop an app for Windows Phone 7 with using of Caliburn Micro and Reactive Extensions.
The app has a page with a ListBox control:
<Grid x:Name="ContentPanel"
Grid.Row="1"
Margin="12,0,12,0">
<ListBox ItemsSource="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<Views:ItemView Margin="0,12,0,0" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
I'm using the next ItemView as a DataTemplate:
<UserControl ...>
<Grid x:Name="LayoutRoot"
cal:Message.Attach="[Event Tap] = [Action SelectItem]">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0"
Style="{StaticResource PhoneTextLargeStyle}"
Text="{Binding Name}"
TextWrapping="Wrap" />
<TextBlock Grid.Column="1"
Foreground="{StaticResource PhoneDisabledBrush}"
Style="{StaticResource PhoneTextLargeStyle}"
Text="{Binding Id}" />
</Grid>
</UserControl>
And the corresponding ItemViewModel looks like this:
public class ItemViewModel
{
private readonly INavigationService _navigationService;
public int Id { get; private set; }
public string Name { get; private set; }
public ItemViewModel(Item item)
{
Id = item.Id;
Name = item.Name;
_navigationService = IoC.Get<INavigationService>();
}
public void SelectItem()
{
_navigationService.UriFor<MainViewModel>()
.WithParam(x => x.Id, Id)
.Navigate();
}
}
}
The ListBox populates with items:
public class ListViewModel : Screen
{
private readonly IItemsManager _itemsManager;
private List<ItemViewModel> _items;
public List<ItemViewModel> Items
{
get { return _items; }
private set
{
_items = value;
NotifyOfPropertyChange(() => Items);
}
}
public ListViewModel(IItemsManager itemsManager)
{
_itemsManager = itemsManager;
}
protected override void OnViewReady(object view)
{
base.OnViewReady(view);
Items = null;
var list = new List<ItemViewModel>();
_itemsManager.GetAll()
.SubscribeOn(ThreadPoolScheduler.Instance)
.ObserveOnDispatcher()
.Subscribe((item) => list.Add(new ItemViewModel(item)),
(ex) => Debug.WriteLine("Error: " + ex.Message),
() =>
{
Items = list;
Debug.WriteLine("Completed"));
}
}
}
And here the problems begin.
_itemsManager returns all items correctly. And all items correctly displayed in the ListBox. There is ~150 items.
When I tap on an item then SelectItem method in the corresponding ItemViewModel must be called. And all works fine for first 10-20 items in ListBox. But for all the next items SelectItem method is called in absolutely incorrect ItemViewModel. For example, I tap on item 34 and SelectItem method is called for item 2, I tap 45 - method is called for item 23, and so on. And there is no no dependence between items.
I already head breaks in search of bugs. In what could be the problem?
The solution was found after reading the discussion forum and the page in documentation of Caliburn.Micro.
All problems were because of Caliburn.Micro's Conventions.
To solve the problem I've added to the DataTempalate the next code: cal:View.Model={Binding}. Now part of the page with the ListBox looks like this:
<Grid x:Name="ContentPanel"
Grid.Row="1"
Margin="12,0,12,0">
<ListBox ItemsSource="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<Views:ItemView Margin="0,12,0,0" cal:View.Model={Binding}/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
I think it's not a perfect answer. So I'll be glad if someone can provide better answer and explanation.
I am trying to bind a list of string values to a listbox so that their values are listed line by line. Right now I use this:
<ListBox Margin="20" ItemsSource="{Binding Path=PersonNames}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Id}"></TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
But I don't know what I am supposed to put into the textblock, instead of Id, since they are all string values, not custom classes.
Also it complains not having to find the PersonNames when I have it inside MainPage, as MainPage.PersonNames.
I set the data context to:
DataContext="{Binding RelativeSource={RelativeSource Self}}"
I am doing it wrong?
If simply put that your ItemsSource is bound like this:
YourListBox.ItemsSource = new List<String> { "One", "Two", "Three" };
Your XAML should look like:
<ListBox Margin="20" Name="YourListBox">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Update:
This is a solution when using a DataContext. Following code is the viewmodel you will be passing to the DataContext of the page and the setting of the DataContext:
public class MyViewModel
{
public List<String> Items
{
get { return new List<String> { "One", "Two", "Three" }; }
}
}
//This can be done in the Loaded event of the page:
DataContext = new MyViewModel();
Your XAML now looks like this:
<ListBox Margin="20" ItemsSource="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
The advantage of this approach is that you can put a lot more properties or complex objects in the MyViewModel class and extract them in the XAML. For example to pass a List of Person objects:
public class ViewModel
{
public List<Person> Items
{
get
{
return new List<Person>
{
new Person { Name = "P1", Age = 1 },
new Person { Name = "P2", Age = 2 }
};
}
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
And the XAML:
<ListBox Margin="20" ItemsSource="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Name}" />
<TextBlock Text="{Binding Path=Age}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
You should show us the code for PersonNames, and I am not sure I understand your question, but maybe you want to bind it like this:
<TextBlock Text="{Binding Path=.}"/>
or
<TextBlock Text="{Binding}"/>
This will bind to the current element in the list (assuming PersonNames is a list of strings). Otherwise, you will see the class name in the list.
If the items source is enumerable as string-entries, use the following:
<TextBlock Text="{Binding}"></TextBlock>
You can use this syntax on any object. Generally, the ToString() -method will then called to get the value. This is in many cases very handy. But beware that no change notification will occur.
You can do this without having to explicitly define the TextBlock control as a part of your ListBox (unless you want better formatting). The trick to getting the binding to trigger is using an ObservableCollection<string> instead of List<string>
Window1.xaml
<ListView Width="250" Height="50" ItemsSource="{Binding MyListViewBinding}"/>
Window1.xaml.cs
public Window1()
{
InitializeComponent();
DataContext = this;
// Need to initialize this, otherwise you get a null exception
MyListViewBinding = new ObservableCollection<string>();
}
public ObservableCollection<string> MyListViewBinding { get; set; }
// Add an item to the list
private void Button_Click_Add(object sender, RoutedEventArgs e)
{
// Custom control for entering a single string
SingleEntryDialog _Dlg = new SingleEntryDialog();
// OutputBox is a string property of the custom control
if ((bool)_Dlg.ShowDialog())
MyListViewBinding.Add(_Dlg.OutputBox.Trim());
}