C# How to check all checkboxes on listview - c#

How to check all checkboxes on listview?
Listview xaml:
<ListView x:Name="List" HorizontalAlignment="Left" Height="559" Margin="10,10,0,0" VerticalAlignment="Top" Width="607" Grid.ColumnSpan="2" ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollBarVisibility="Auto" IsMouseCapturedChanged="List_IsMouseCapturedChanged">
<ListView.ContextMenu>
<ContextMenu>
<MenuItem Name="Dodaj" Header="Dodaj" Click="DodajUtwor_Click"/>
<MenuItem Name="Usuń" Header="Usuń Zaznaczone" Click="UsuńUtwór_Click"/>
<MenuItem Name="Clear" Header="Wyczyść Listę" Click="ClearList_Click"/>
<MenuItem Name="Check" Header="Zaznacz Wszystkie" Click="SelectAll_Click"/>
</ContextMenu>
</ListView.ContextMenu>
<ListView.View>
<GridView>
<GridViewColumn Width="30" >
<GridViewColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox Name="CheckBox" Padding="10" IsChecked="{Binding IsChecked}"/>
<TextBlock Text="{Binding Data}"/>
</StackPanel>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Nazwa Pliku" Width="100" DisplayMemberBinding="{Binding Nazwa}" />
<GridViewColumn Header="Tytuł" Width="100" DisplayMemberBinding="{Binding Tytuł}"/>
<GridViewColumn Header="Wykonawca" Width="100" DisplayMemberBinding="{Binding Autor}"/>
<GridViewColumn Header="Album" Width="100" DisplayMemberBinding="{Binding Album}"/>
<GridViewColumn Header="Nr" Width="100" DisplayMemberBinding="{Binding Nr}"/>
<GridViewColumn Header="Rok" Width="100" DisplayMemberBinding="{Binding Rok}"/>
<GridViewColumn Header="Gatunek" Width="100" DisplayMemberBinding="{Binding Gatunek}"/>
<GridViewColumn Header="Komantarze" Width="100" DisplayMemberBinding="{Binding Komentarze}"/>
<GridViewColumn Header="Okładka" Width="100" DisplayMemberBinding="{Binding Okładka}"/>
<GridViewColumn Header="Lokalizacja" Width="100" DisplayMemberBinding="{Binding Lokalizacja}"/>
</GridView>
</ListView.View>
</ListView>
Code:
private void Button_Click(object sender, RoutedEventArgs e)
{
MyItem selectedItem = (MyItem)this.List.SelectedItem;
selectedItem.IsChedked = true;
List.Items.Refresh();
}
Don't work.
I want to change all checkboxes on true in a listviev. I dont know how to use loop foreach. And how to delete items witch checkboxes on true?

I guess you might be looking for a checkbox in the header column and select all grid items when header checkbox got selected.
We can do this having simple child/sub viewmodels. Below code might help/solve your problem.
Xaml/View code -
<GridViewDataColumn DataMemberBinding="{Binding IsChecked}" >
<GridViewDataColumn.Header >
<CheckBox HorizontalAlignment="Left" IsChecked="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type GridViewDataControl}}
,Path=DataContext.CheckAll}"
Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type GridViewDataControl}}
,Path=DataContext.CheckAllCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=IsChecked}" />
</GridViewDataColumn.Header>
<GridViewDataColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox Name="CheckBox" Padding="10" IsChecked="{Binding IsChecked}" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type GridViewDataControl}}
,Path=DataContext.ItemCommand}" CommandParameter="{Binding}"/>
<TextBlock Text=y"{Binding Data}"/>
</StackPanel>
</DataTemplate>
</GridViewDataColumn.CellTemplate>
</GridViewDataColumn>
and you can have your view models as explained below.
class MainViewModel : Common.UserInterface.ViewModelBase, IDisposable
{
public MainViewModel()
{
CheckAllCommand = new DelegateCommand<bool>(OnCheckAllExecuted);
}
void OnCheckAllExecuted(bool status)
{
// Your logic goes here (if any)
CheckAll = items.All(item => item.IsChecked);
}
public DelegateCommand<ItemViewModel> ItemCommand { get; private set; }
private bool checkAll;
private ObservableCollection<ItemViewModel> items;
public DelegateCommand<bool> CheckAllCommand
{
get;
private set;
}
public ObservableCollection<ItemViewModel> Items
{
get
{
return items;
}
set
{
items = value;
OnPropertyChanged(() => Items);
}
}
public bool CheckAll
{
get { return checkAll; }
set
{
checkAll = value;
OnPropertyChanged(() => CheckAll);
}
}
}
class ItemViewModel : ViewModelBase
{
public bool ischecked;
public string data;
public new bool IsChecked
{
get { return isChecked; }
set
{
isChecked = value;
OnPropertyChanged("IsChecked");
}
}
public string Data
{
get { return data; }
set
{
data = value;
OnPropertyChanged("Data");
}
}
}

Related

C# WPF - Command Binding of toggle button not working

Good day,
I would like to ask question on how to properly bind the RelayCommand UpdateUserCommand() in toggle button. Please see my code below
<UserControl x:Class="istock.View.UserMasterList"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:local="clr-namespace:istock.View"
mc:Ignorable="d"
MinHeight="450" Width="Auto" MinWidth="1024" FontFamily="Segoe UI LIght">
<Grid>
<Border Padding="30 15">
<StackPanel>
<Grid>
<TextBlock Text="User Management" FontSize="20" HorizontalAlignment="Left" Width="Auto" />
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Width="Auto">
<Button x:Name="btnNew" Foreground="#FFFF">
<StackPanel Orientation="Horizontal">
<materialDesign:PackIcon Kind="PlusBoxOutline" Margin="0 5" />
<TextBlock Text="New User" Margin="5 3 5 0" />
</StackPanel>
</Button>
</StackPanel>
</Grid>
<ListView ItemsSource="{Binding Path = UserMasterListProp}">
<ListView.View>
<GridView>
<GridViewColumn Header="ID" Width="auto" DisplayMemberBinding="{Binding Path = Id}"></GridViewColumn>
<GridViewColumn Header="Username" Width="120" DisplayMemberBinding="{Binding Path = Username}"></GridViewColumn>
<GridViewColumn Header="Firstname" Width="120" DisplayMemberBinding="{Binding Path = Firstname}"></GridViewColumn>
<GridViewColumn Header="Middlename" Width="120" DisplayMemberBinding="{Binding Path = Middlename}"></GridViewColumn>
<GridViewColumn Header="Lastname" Width="120" DisplayMemberBinding="{Binding Path = Lastname}"></GridViewColumn>
<GridViewColumn Header="Role" Width="100" DisplayMemberBinding="{Binding Path = Role}"></GridViewColumn>
<GridViewColumn Header="Activated">
<GridViewColumn.CellTemplate>
<DataTemplate>
<ToggleButton x:Name="tbtnActivated" Style="{DynamicResource MaterialDesignSwitchToggleButton}" IsChecked="{Binding Path = Activated}" Command="{Binding Path = UserViewModel.UpdateUserCommand}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Locked">
<GridViewColumn.CellTemplate>
<DataTemplate>
<ToggleButton x:Name="tbtnLocked" Style="{DynamicResource MaterialDesignSwitchToggleButton}" IsChecked="{Binding Path = Locked}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</StackPanel>
</Border>
</Grid>
Here is my Command Code which was initialized and CanExecute() method is always true.
public class RelayCommand : ICommand
{
private Action ExecuteCmd;
public RelayCommand(Action paramAction)
{
this.ExecuteCmd = paramAction;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
this.ExecuteCmd();
}
}
And Here's my code in ViewModel which the UpdateUser() method will be fired
by my UpdateUserCommand()
#region Update Command and Method
private RelayCommand updateUserCommand;
public RelayCommand UpdateUserCommand
{
get { return updateUserCommand; }
}
public void UpdateUser()
{
try
{
var isExist = this.userService.ApplyService_FindByIdOrUsername(UserModel.Id, UserModel.Username);
if(isExist == null)
{
var isUpdated = this.userService.ApplyService_Update(UserModel);
if (isUpdated == true)
{
this.Message = "Update sucesss.";
this.Populate_UserMasterList();
}
}
else
{
this.Message = "Update failed. ID or Username already exist.";
return;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message.ToString());
return;
}
}
#endregion
Here is the implementation of the Data Context in Code Behind of the User Control
public partial class UserMasterList : UserControl
{
public UserMasterList()
{
InitializeComponent();
UserViewModel userViewModel = new UserViewModel();
this.DataContext = userViewModel;
}
}
Please help. If ever my code is confusing, I am open for question. Thanks
You could bind to a property of the parent UserControl using a {RelativeSource}:
<ToggleButton x:Name="tbtnActivated"
Style="{DynamicResource MaterialDesignSwitchToggleButton}"
IsChecked="{Binding Activated}"
Command="{Binding DataContext.UpdateUserCommand,
RelativeSource={RelativeSource AncestorType=UserControl}}" />

Binding Listview SelectedItems for Actions

I'm struggling to bind 2 listviews selected items to my viewmodel.
The idea is to have a view with 2 listviews and 2 buttons in between to move the (multiple) selected items from 1 listview to another (2 way).
The view:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ListView x:Name="DuamResources" Grid.Column="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<ListView.View>
<GridView>
<GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}"/>
<GridViewColumn Header="Description" DisplayMemberBinding="{Binding Name}"/>
</GridView>
</ListView.View>
<ListView.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<TextBlock FontWeight="Bold" FontSize="14" Text="{Binding Name}"/>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ListView.GroupStyle>
</ListView>
<StackPanel Grid.Column="1" Orientation="Vertical" cal:Action.TargetWithoutContext="{Binding SelectedDuamResources}" VerticalAlignment="Center">
<Button Content="<" Width="40" Margin="5" cal:Message.Attach="AddSelectedResources($datacontext)"/>
<Button Content=">" Width="40" Margin="5"/>
</StackPanel>
<ListView x:Name="AvailableDuamResources" Grid.Column="2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<ListView.View>
<GridView>
<GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}"/>
<GridViewColumn Header="Description" DisplayMemberBinding="{Binding Name}"/>
</GridView>
</ListView.View>
<ListView.GroupStyle>
<GroupStyle HidesIfEmpty="True">
<GroupStyle.HeaderTemplate>
<DataTemplate>
<TextBlock FontWeight="Bold" FontSize="14" Text="{Binding Type}"/>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ListView.GroupStyle>
</ListView>
</Grid>
The associated viewmodel properties:
private ObservableCollection<DuamResourceInfo> availableDuamResources;
public ObservableCollection<DuamResourceInfo> AvailableDuamResources
{
get { return availableDuamResources; }
set { availableDuamResources = value; NotifyOfPropertyChange(() => AvailableDuamResources); }
}
private ObservableCollection<DuamResourceInfo> selectedDuamResources;
public ObservableCollection<DuamResourceInfo> SelectedDuamResources
{
get { return selectedDuamResources; }
set { selectedDuamResources = value; NotifyOfPropertyChange(() => SelectedDuamResources); }
}
private ObservableCollection<DuamResourceInfo> duamResources;
public ObservableCollection<DuamResourceInfo> DuamResources
{
get { return duamResources; }
set { duamResources = value; NotifyOfPropertyChange(() => DuamResources); }
}
The code I want to achieve:
public void AddSelectedResources(IEnumerable<DuamResourceInfo> resources)
{
}
public void RemoveSelectedResources(IEnumerable<DuamResourceInfo> resources)
{
}
I'm using Caliburn Micro for MVVM. I know there are some conventions for binding but I'm not sure they apply to this scenario.
Any help is greatly appreciated!
Have you tried using "x:Bind" instead of "Binding"? For some reason in the past one or the other has worked for me, but not both, depending on the situation.

Bind Combox inside a ListView

I have created a ListView with a ComboBox
<ListView x:Name="lstvAttendance" Margin="0,53,0,10">
<ListView.View>
<GridView>
<GridViewColumn Header="ID" Width="0" DisplayMemberBinding="{Binding Path=Id}"/>
<GridViewColumn Header="Emp Code" Width="100" DisplayMemberBinding="{Binding Path=emp_id}"/>
<GridViewColumn Header="Employee Name" Width="160" DisplayMemberBinding="{Binding Path=name}"/>
<GridViewColumn Header="Status" Width="90">
<GridViewColumn.CellTemplate>
<DataTemplate>
<ComboBox x:Name="cmbStatus" Width="75" Text="{Binding Path=status}" SelectedItem="{Binding Path=status}">
<ComboBoxItem Content="P"/>
<ComboBoxItem Content="A"/>
</ComboBox>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Date" Width="135">
<GridViewColumn.CellTemplate>
<DataTemplate>
<DatePicker x:Name="dtpDate" Width="120" Text="{Binding attendance_date}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Reg Date" Width="140" DisplayMemberBinding="{Binding Path=reg_date}"/>
<GridViewColumn Header="Last Update" Width="140" DisplayMemberBinding="{Binding Path=last_update}"/>
<GridViewColumn Header="Delete" Width="70">
<GridViewColumn.CellTemplate>
<DataTemplate>
<Button x:Name="btnRemove" Content="Remove" Width="60" BorderThickness="0" CommandParameter="{Binding}" HorizontalContentAlignment="Right" Style="{StaticResource DelImg}" Cursor="Hand" Foreground="Blue"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
I need to Bind this ComboBox(ComboBox has either P or A).For Binding these ListView from DataBase I created a class Attendance.
public class Attendance
{
public string Id { get; set; }
public string emp_id { get; set; }
public string name { get; set; }
public string status { get; set; } //Either P or A
public string attendance_date { get; set; }
public string reg_date { get; set; }
public string last_update { get; set; }
}
And then:
try
{
using (SqlConnection con = new SqlConnection(DBCon.conStr))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(AppConstraints.LIST_VIEW_ATTENDANCE))
{
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
lstvAttendance.Items.Add(new Attendance()
{
Id = dr["Id"].ToString(),
emp_id = dr["emp_id"].ToString(),
name = dr["name"].ToString(),
attendance_datedr["attendance_date"].ToString(),
status = dr["status"].ToString(),
reg_date = dr["reg_date"].ToString(),
last_update = dr["last_update"].ToString()
});
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
My code works for other fields in ListView. But ComboBox value not select. I need help to select ComboBox value with respect to Database value.
Firstly:Create a List of Attendance instead of adding items to lstvAttendance and then set the lstvAttendance's ItemsSource like this:
List<Attendance> lst = new List<Attendance>();
try
{
....
....
while (dr.Read())
{
lst.Add(new Attendance()
{
....
}
}
...
...
lstvAttendance.ItemsSource = lst;
}
catch
{
....
}
Secondly: You missed the ItemsSource property of your ComboBox it should be like this:
<ComboBox x:Name="cmbStatus" Width="75" DisplayMemberPath="status"
ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=ListView}, Path=ItemsSource}"
SelectedValuePath="status" SelectedValue="{Binding Path=status}">
</ComboBox>
You should use SelectedValuePath binding then bind to the SelectedValue=status property of viewModel.
Binding to SelectedItem will always contain the actually selected item ( ComboBoxItem) not the actual value.
<ComboBox x:Name="cmbStatus" Width="75" SelectedValuePath="{Binding Path=Content}" SelectedValue="{Binding Path=status}">
<ComboBoxItem Content="P"/>
<ComboBoxItem Content="A"/>
</ComboBox>

WPF-MVVM Radio Button generated automatically

I have an application where I present a Form. The form contains multiple Radio Buttons and they are displayed 1 next to each other. I need to load the colors from the list and create a radio button for each color, then when the users selects a color I want to grab the "SelectedItem" from the control. I know you can do that easily with a list but how do I do that when I need to place the controls next to each other ??
Code :
<Grid>
<StackPanel VerticalAlignment="Top">
<GroupBox Name="CheckBoxes" Margin="5" >
<StackPanel Name="wrpCheckBoxes" DataContext="{Binding ListParts}">
<RadioButton Name="chkRed" Content="{Binding Description}" Visibility="{Binding DataBindingModel.ColorRed}" Tag="{Binding ID}" />
<RadioButton Name="chkGreen" Content="Green" Visibility="{Binding DataBindingModel.ColorGreen}" />
<RadioButton Name="chkBlue" Content="Blue" Visibility="{Binding DataBindingModel.ColorBlue}" />
<RadioButton Name="chkGray" Content="Gray" Visibility="{Binding DataBindingModel.ColorGray}" />
<RadioButton Name="chkYellow" Content="Yellow" Visibility="{Binding DataBindingModel.ColorYellow}" />
<RadioButton Name="chkBlack" Content="Black" Visibility="{Binding DataBindingModel.ColorBlack}" />
</StackPanel>
</GroupBox>
</StackPanel>
<StackPanel VerticalAlignment="Bottom" Margin="5">
<ListView x:Name="listBoxItems" BorderThickness="1" ItemsSource="{Binding ListParts}">
<ListView.View>
<GridView>
<GridViewColumn Header="Index" DisplayMemberBinding="{Binding Index}" />
<GridViewColumn Header="Description" DisplayMemberBinding="{Binding Description}" />
<GridViewColumn Header="Price" DisplayMemberBinding="{Binding Price}" />
</GridView>
</ListView.View>
</ListView>
<!--<ListBox x:Name="listBoxItems" ItemsSource="{Binding ListParts}">
<ListBox.ItemTemplate>
<DataTemplate>
<RadioButton GroupName="rbList" Tag="{Binding}" Content="{Binding Description}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>-->
</StackPanel>
</Grid>
Remark : the ListParts is just a list containing the colors, also this view is attached to a viewModel
ViewModel :
public class DataBindingViewModel : ViewModelBase
{
#region Private Fields
private DataBindingModel _DataBindingModel;
private List<PartsModel> _ListParts;
private string _Description1;
private int _TagID;
#endregion
#region Properties
public DataBindingModel DataBindingModel
{
get { return this._DataBindingModel; }
set
{
if (this._DataBindingModel == value)
return;
this._DataBindingModel = value;
OnPropertyChanged("DataBindingModel");
}
}
public List<PartsModel> ListParts
{
get { return this._ListParts; }
set
{
if (this._ListParts == value)
return;
this._ListParts = value;
OnPropertyChanged("ListParts");
}
}
public string Description1
{
get { return this._Description1; }
set
{
if (this._Description1 == value)
return;
this._Description1 = value;
OnPropertyChanged("Description1");
}
}
public int TagID
{
get { return this._TagID; }
set
{
if (this._TagID == value)
return;
this._TagID = value;
OnPropertyChanged("TagID");
}
}
#endregion
public DataBindingViewModel(DataBindingModel DataBinding)
{
this.DataBindingModel = DataBinding;
this.ListParts = Common.GetData();
}
}
And the Common Class is just laoding the Data :
public static class Common
{
public static List<PartsModel> GetData()
{
List<PartsModel> listParts = new List<PartsModel>();
listParts.Add(new PartsModel(1, "1234561", "Color Red", Convert.ToDecimal(15.99)));
listParts.Add(new PartsModel(2, "1234562", "Color Green", Convert.ToDecimal(17.00)));
listParts.Add(new PartsModel(3, "1234563", "Color Blue", Convert.ToDecimal(12.95)));
listParts.Add(new PartsModel(4, "1234564", "Color Gray", Convert.ToDecimal(9.95)));
listParts.Add(new PartsModel(5, "1234565", "Color Yellow", Convert.ToDecimal(10.55)));
listParts.Add(new PartsModel(6, "1234566", "Color Black", Convert.ToDecimal(99.99)));
return listParts;
}
}
How can I display the members of the ListParts on each of my radio button, without the use of a ListView ?
Let me know if you guys need more info and thanks for the answers
You can use ListBox.ItemsPanel to specify the type of panel you want - probably <StackPanel Orientation="Horizontal/>.
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<RadioButton GroupName="rbList" Tag="{Binding}" Content="{Binding Description}" />
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"
VerticalAlignment="Center"
HorizontalAlignment="Center"/>
</ItemsPanelTemplate>
<ListBox.ItemsPanel>
<ListBox>
See the examples in the ItemsPanel property documentation on MSDN for more information.

WPF Listview databinding to generic List, dynamically filled by WCF service

In WPF app I have a WCF service which dynamically fills a generic List object from a backend database.
How in this case (List created in runtime), I could bind List items to a ListView object items?
It is the Data contract for my Web service:
....
[DataContract]
public class MeetList
{
[DataMember]
public string MeetDate;
[DataMember]
public string MeetTime;
[DataMember]
public string MeetDescr;
.....
static internal List<MeetList> LoadMeetings(string dynamicsNavXml)
{
...// Loads XML stream into the WCF type
}
Here in this event handler I read the WCF service and Loop through a List object:
private void AllMeetings()
{
Customer_ServiceClient service = new Customer_ServiceClient();
foreach (MeetList meet in service.ReadMeetList())
{
?????? = meet.MeetDate; // it's here that I bumped into a problem
?????? = meet.MeetTime; //
?????? = meet.MeetDescr;//
}
}
My Listview XAML:
<Grid>
<ListView Height="100" Width="434" Margin="0,22,0,0" Name="lvItems" ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True" SelectionMode="Single">
<ListView.View>
<GridView>
<GridViewColumn Header="Date" Width="100" HeaderTemplate="{StaticResource DateHeader}" CellTemplate="{DynamicResource DateCell}"/>
<GridViewColumn Header="Time" Width="100" HeaderTemplate="{StaticResource TimeHeader}" CellTemplate="{DynamicResource TimeCell}"/>
<GridViewColumn Header="Description" Width="200" HeaderTemplate="{StaticResource DescriptionHeader}" CellTemplate="{DynamicResource DescriptionCell}"/>
</GridView>
</ListView.View>
</ListView>
</Grid>
And data templates for this ListView:
<Window.Resources>
<DataTemplate x:Key="DateHeader">
<StackPanel Orientation="Horizontal">
<TextBlock Margin="10,0,0,0" Text="Date" VerticalAlignment="Center" />
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="DateCell" DataType="Profile">
<StackPanel Orientation="Horizontal">
<TextBlock>
<TextBlock.Text>
<Binding Path="MeetDate" />
</TextBlock.Text>
</TextBlock>
</StackPanel>
</DataTemplate>
......
How in this case (List created in runtime), I could bind my generic List items to a ListView object items?
I tried to use lvItems.ItemsSource = profiles; , but it doesn't work in my event handler
List doesn't have behaviour to notify that items count is changed. You should use a list with support INotifyCollectionChanged.. for example: ObservableCollection<T>. ObservableCollection<T> will inform your lvItems that items count is changed and it will be properly display.
Using intermediate ObservableCollection:
ObservableCollection<Meets> _MeetCollection =
new ObservableCollection<Meets>();
public ObservableCollection<Meets> MeetCollection
{ get { return _MeetCollection; } }
public class Meets
{
public string Date { get; set; }
public string Time { get; set; }
public string Description { get; set; }
}
In the event handler loop we put:
private void AllMeetings()
{
Customer_ServiceClient service = new Customer_ServiceClient();
_MeetCollection.Clear();
foreach (MeetList meet in service.ReadMeetList())
{
_MeetCollection.Add(new Meets
{
Date = meet.MeetDate,
Time = meet.MeetTime,
Description = meet.MeetDescr
});
}
}
And XAML binding is changed to:
<Grid>
<ListView Height="100" Width="434" Margin="0,22,0,0" Name="lvItems" ItemsSource="{Binding MeetCollection}">
<ListView.View>
<GridView>
<GridViewColumn Header="Date" Width="100" DisplayMemberBinding="{Binding Date}"/>
<GridViewColumn Header="Time" Width="100" DisplayMemberBinding="{Binding Time}"/>
<GridViewColumn Header="Description" Width="200" DisplayMemberBinding="{Binding Description}"/>
</GridView>
</ListView.View>
</ListView>
</Grid>

Categories