using UserControl as item template for ItemsControl - c#

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.

Related

How to bind ItemsControl of Labels to an ObservableCollection

I have an ItemsControl who has an ItemsSource that is an ObservableCollection. The DataTemplate contains Label controls. My goal is to set the Content property of each of these Labels to the elements in the ObservableCollection but right now, the Content is entirely blank for each of the Label.
It is worth noting that this ItemsControl is nested within another, parent ItemsControl, but let me show:
<ItemsControl ItemsSource={Binding StudentCollection}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="90"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
// This is the ItemsControl that is not working properly with the Labels
<ItemsControl ItemsSource="{Binding StudentActivitiesCollection}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Label Content="{Binding Sport, UpdatedSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</DataTemplate>
</ItemsControl.Template>
</ItemsControl>
This is my StudentsActivities class:
public class StudentActivities : INotifyPropertyChanged
private string sport;
public string Sport
{
get
{
return this.sport;
}
set
{
this.sport = value;
OnPropertyChanged("Sport");
}
}
}
}
And my working View Model:
private ObservableCollection<StudentActivities> studentActivitiesCollection;
public ObservableCollection<StudentActivities> StudentActivitiesCollection
{
get
{
if (studentActivitiesCollection == null)
studentActivitiesCollection = new ObservableCollection<StudentActivities>();
return studentActivitiesCollection;
}
}
This is the method I am using to populate my ObservableCollection in my ViewModel:
private void PopulateStudentActivitiesCollection(ObservableCollection<Student> Students)
{
foreach (Student s in Students)
{
StudentActivitiesCollection.Add(new StudentActivities () { Sport = StudentSport });
}
}
}
Change
<ItemsControl ItemsSource={StudentCollection}">
to
<ItemsControl ItemsSource={Binding StudentCollection}">
and
<Label Content="{Binding Sport, UpdatedSourceTrigger=PropertyChanged}"/>
to
<Label Content="{Binding Sport}"/>
The last change is not needed but not necessary either.

Windows phone 8 DataTemplate in XAML not showing data

I would like to display some information in a data template in my app but when it is run it shows nothing in the listbox.
Here is the class code (class called notes)
public class notes
{
public string strNoteName { get; set; }
public string strCreated { get; set; }
public string strModified { get; set; }
public bool boolIsProtected { get; set; }
public string strNoteImage { get; set; }
public static ObservableCollection<notes> GetnotesRecord()
{
ObservableCollection<notes> notesRecord = new ObservableCollection<notes>
{
new notes{strNoteName="Science",strCreated="17/07/2014",strModified="17/07/2014",boolIsProtected=true,strNoteImage=""},
new notes{strNoteName="Math",strCreated="12/02/2014",strModified="15/07/2014",boolIsProtected=false,strNoteImage=""},
new notes{strNoteName="HW",strCreated="05/06/2014",strModified="2/07/2014",boolIsProtected=false,strNoteImage=""},
new notes{strNoteName="Business",strCreated="23/04/2014",strModified="17/07/2014",boolIsProtected=true,strNoteImage=""},
};
return notesRecord;
}
public ObservableCollection<notes> _notes;
public ObservableCollection<notes> allNotes
{
get
{
return _notes;
}
set
{
_notes = value;
}
}
}
And here is the XAML code:
<ListBox Margin="0,10,0,88">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Grid Margin="0,5,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Image Source="{Binding strNoteImage}" Height="80" Width="80" Grid.Column="0"></Image>
<StackPanel Grid.Column="1" Orientation="Vertical" Width="150" Height="100" >
<TextBlock Text="{Binding strNoteName}" Margin="5,1,0,1"></TextBlock>
<TextBlock Text="{Binding strCreated}" Margin="5,1,0,1"></TextBlock>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Last modified: " Margin="5,1,0,1"></TextBlock>
<TextBlock Text="{Binding strModified}" Margin="3,1,0,1"></TextBlock>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Is protected: " Margin="5,1,0,1"></TextBlock>
<TextBlock Text="{Binding boolIsProtected}" Margin="3,1,0,1"></TextBlock>
</StackPanel>
</StackPanel>
</Grid>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox >
Thank you in advance for any help :)
Change the ListBox definition to
<ListBox Margin="0,10,0,88" ItemsSource="{Binding}">
and set in C# code
this.DataContext = Notes.GetnotesRecord();
You are missing to set the ItemsSource to the Listbox,
You can do that in XAML and set the DataContext in code behind , Something like this,
<ListBox Margin="0,10,0,88" Name = "lstBox1" ItemsSource= "{Binding}" />
In code behind,
This.DataContext = GetnotesRecord();
Or
lstBox1.ItemsSource = GetnotesRecord();

Maintaining the collection in a List/ObservableCollection

i have been successfully adding an item to list in a MVVM, and now my problem is maintaining the list in the view model. Every time i navigate to a page or go back to a page and return to that listview, the list resets. how will i able to achieve that? i am currently using the prism to build the MVVM.
The ViewModel:
public ObservableCollection<CartData> _cartData;
public ObservableCollection<CartData> CartData
{
get {
return _cartData;
}
set {
SetProperty(ref _cartData, value);
}
}
private DelegateCommand _addItemCommand;
public ICommand AddItemCommand
{
get
{
if (_addItemCommand == null)
{
_addItemCommand = new DelegateCommand(AddToCart);
}
return _addItemCommand;
}
}
public void AddToCart() {
CartData.Add(new CartData { Cakename = "Black Forest", Cakeprice = 104 });
}
View:
.....
<Page.DataContext>
<vm:CartingDataSource/>
</Page.DataContext>
....
<ListView
x:Name="itemListView"
AutomationProperties.AutomationId="ItemsListView"
AutomationProperties.Name="Items"
TabIndex="1"
Margin="-10,130,0,264"
Padding="120,0,0,60"
ItemsSource="{Binding cartData}"
IsSwipeEnabled="False" Grid.RowSpan="2" ItemClick="itemListView_ItemClick" SelectionChanged="itemListView_SelectionChanged_1" IsItemClickEnabled="True">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Margin="6">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Border Background="{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}" Width="60" Height="60">
<Image Stretch="UniformToFill" AutomationProperties.Name="{Binding Title}" Source="Assets/wewewew.jpg"/>
</Border>
<StackPanel Grid.Column="1" Margin="10,0,0,0">
<TextBlock Text="{Binding Cakename}" Style="{StaticResource TitleTextBlockStyle}" TextWrapping="NoWrap" MaxHeight="40"/>
<TextBlock Text="{Binding Cakeprice}" Style="{StaticResource CaptionTextBlockStyle}" TextWrapping="NoWrap"/>
</StackPanel>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.ItemContainerStyle>
<Style TargetType="FrameworkElement">
<Setter Property="Margin" Value="0,0,0,10"/>
</Style>
</ListView.ItemContainerStyle>
</ListView>
Here if your ViewModel is CartingDataSource in that case it is being instatiated on every page load. Now if that is the case, then you are creating a new instance of your collection in your constructor as below:
public CartingDataSource() {
CartData = new ObservableCollection<CartData>();
}
As a result of which it re-initializes your collection.
You need to remove the initialization from your constructor and do something like this:
public ObservableCollection<CartData> _cartData;
public ObservableCollection<CartData> cartData
{
get {
if(_cartData == null)
{
_cartData = new ObservableCollection<CartData>();
}
return _cartData;
}
set {
_cartData = value;
}
}

Dependency Property inner Binding in custom control

I'm trying to bind the ItemsSource property of an ItemsControl contained in my UserControl (a group of radiobuttons) to a property of the same UserControl. This should be driven by the DependencyProperty when the UserControl is used. But I am not able to make it work, if instead I hardcode the control name the assignment works correctly.
This is the class :
public partial class GroupListBox : UserControl
{
public GroupListBox()
{
InitializeComponent();
}
private List<RadioButton> _itemsList = new List<RadioButton>();
public List<RadioButton> ItemsList
{
get { return _itemsList; }
set
{
_itemsList = value;
}
}
public IEnumerable ItemsSource
{
get { return (IEnumerable)GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
public static readonly DependencyProperty ItemsSourceProperty =
DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(GroupListBox), new FrameworkPropertyMetadata(null, OnItemsSourceChanged));
private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var control = (GroupListBox)d;
var grpName = control.GetHashCode().ToString(); // used to generate a unique GroupName
var oldValue = (IEnumerable)e.OldValue;
var newValue = (IEnumerable)e.NewValue;
if ((e.NewValue == null) && !BindingOperations.IsDataBound(d, ItemsSourceProperty))
{
control.ItemsList.Clear();
}
else
{
var radioItems = (from object item in newValue select new RadioButton() { Content = item, GroupName = grpName }).ToList();
//control.container.ItemsSource = radioItems; // *** this works
control.ItemsList = radioItems; // *** this doesn`t
}
}
this is the XAML
<Border x:Name="brdMain">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock x:Name="txtTitle" Grid.Column="1" Grid.ColumnSpan="2" Grid.Row="0" Text="" />
<Image x:Name="imgImage" Grid.Column="0" Grid.Row="1" />
<ScrollViewer x:Name="scroll" Grid.Row="1" Grid.Column="1" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" CanContentScroll="True">
<!--This is the control I want to bind-->
<ItemsControl x:Name="container" ItemsSource="{Binding Path=ItemsList}" >
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</ScrollViewer>
</Grid>
</Border>
used like this:
<cust:GroupListBox ItemsSource="{Binding SymmetryAxis}"></cust:GroupListBox>
I'm sure there is something wrong with my control binding but I don`t know what.
Any clue?
EDIT :
I did some little change in the XAML :
now it looks like this :
<ItemsControl Name="container" Width="{Binding ElementName=scroll, Path=ViewportWidth}" ItemsSource="{Binding Path=ItemsSource, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:GroupListBox}}}" ItemTemplate="{StaticResource ItemPanelDatatemplate}" />
and this is the DataTemplate :
<DataTemplate DataType="{x:Type ItemsPanelTemplate}" x:Key="ItemPanelDatatemplate">
<RadioButton Content="{Binding}" GroupName="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ItemsControl}, Path=Name}"></RadioButton> </DataTemplate>
This anyway gives problems with the GroupName because it`s always empty and then all the RadioButtons act like if they are in a single group.
How can I obtain the same result like in the code behind (for example assigning a unique name for each group?

Wrong item selection in ListBox (Windows Phone, Caliburn.Micro, Rx)

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.

Categories

Resources