I am learning WPF and I am trying to fill a ListView with a list of folders (as ListView Groups) and files for each folder(as ListView Items).
Using WPF/MVVM Quick Start Tutorial , I created the following classes (Business removed)
public class PatchGen
{
public PatchGen() { }
private string _folderName;
private Dictionary<string, string> _filesInfo = new Dictionary<string, string>();
public string FolderName
{
get { return _folderName; }
set { _folderName= value; }
}
public Dictionary<string, string> FilesInfo
{
get { return _filesInfo; }
set { _filesInfo = value; }
}
}
and the ViewModel:
public class PatchGenViewModel : ObservableObject
{
public PatchGenViewModel()
{
}
List<PatchGen> _folderList = new List<PatchGen>();
public List<PatchGen> Folders
{
get
{
return _folderList;
}
set { }
}
void AddFilesExecute()
{
//business here
}
bool CanAddFilesExecute()
{
return true;
}
public ICommand AddFiles { get { return new RelayCommand(AddFilesExecute, CanAddFilesExecute); } }
The xaml section includes the DataContextand the CollectionViewSource:
<Window.DataContext>
<local:PatchGenViewModel></local:PatchGenViewModel>
</Window.DataContext>
<Window.Resources>
<CollectionViewSource x:Key='groups'
Source="{Binding Path=Folders}">
<CollectionViewSource.GroupDescriptions>
<PropertyGroupDescription PropertyName="FolderName" />
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
</Window.Resources>
and the ListView:
<ListView Grid.Row="1"
HorizontalAlignment="Stretch"
Name="lstViewServices"
ItemsSource='{Binding Source={StaticResource groups}}'>
<ListView.View>
<GridView>
<GridViewColumn Header="File Name"
DisplayMemberBinding="{Binding Path=??? }"
Width="100" />
<GridViewColumn Header="File Path"
DisplayMemberBinding="{Binding Path=??? }"
Width="Auto" />
</GridView>
</ListView.View>
</ListView>
The ListView Group is not showing the Folders Names. ?
How to have the File Name and the File Path that represents the FilesInfo (Dictionnary < string,string > ) information displayed?
Is there any way to do this through XAML and ViewModel Class without the Code behind of the Xaml file?
You need to just bind the File name to the File to the folder name property.
For the File Path, you need to bind it to the FilesInfo property. Why is it a dictionary? I guess I didn't understand why you are using a dictionary here? Maybe I am missing something but you should drop the dictionary and create your own little object.
public class FileInfo
{
public string FileName {get;set;}
public string FilePath {get;set;}
}
Then of course change your PatchGen object to use that instead of a Dictionary.
Maybe a screenshot of what you want it to look like would help. However, if you look at your XAML, you don't have anywhere to put your FolderName. You only have places for FileName and FilePath.
<ListView Grid.Row="1"
HorizontalAlignment="Stretch"
Name="lstViewServices"
ItemsSource='{Binding Source={StaticResource groups}}'>
<ListView.View>
<GridView>
<GridViewColumn Header="File Name"
DisplayMemberBinding="{Binding Path=FileName }"
Width="100" />
<GridViewColumn Header="File Path"
DisplayMemberBinding="{Binding Path=FilePath}"
Width="Auto" />
</GridView>
</ListView.View>
</ListView>
So you should add a place for FolderName. You have two lists it seems: the folder list and for each folder a the file list. But your view only has one level.
Here is an example that has two levels.
<ItemsControl ItemsSource='{Binding Folders}'>
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<Label Content="{Binding FolderName}" />
<ListView Grid.Row="1"
HorizontalAlignment="Stretch"
Name="lstViewServices"
ItemsSource="FileInfo">
<ListView.View>
<GridView>
<GridViewColumn Header="File Name"
DisplayMemberBinding="{Binding Path=FolderName}"
Width="100" />
<GridViewColumn Header="File Path"
DisplayMemberBinding="{Binding Path=FolderName }"
Width="Auto" />
</GridView>
</ListView.View>
</ListView>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Related
As someone who has recently switched from WinForms to WPF, I'm still struggling and going nuts trying to figure out a way to loop through and delete checked ListView items.
This method gives me error: "ListView does not contain a definition for CheckedItems..."
if (lvFilesList != null)
{
foreach (ListViewItem lvItem in lvFilesList.CheckedItems)
{
lvItem.Checked = False;
}
}
My XAML Code:
<ListView Height="400" Width="400"
Name="lvFilesList"
ItemsSource="{Binding}"
IsSynchronizedWithCurrentItem="True">
<ListView.View>
<GridView>
<GridView.Columns>
<GridViewColumn>
<GridViewColumn.CellTemplate>
<DataTemplate>
<CheckBox Name="chk" IsChecked="{Binding IsChecked, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></CheckBox>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="ID" DisplayMemberBinding="{Binding ID}"/>
<GridViewColumn Header="File" DisplayMemberBinding="{Binding File}"/>
<GridViewColumn Header="Author" DisplayMemberBinding="{Binding Author}"/>
</GridView.Columns>
</GridView>
</ListView.View>
<ListView.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<TextBlock FontWeight="Bold" Text="Group"/>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ListView.GroupStyle>
</ListView>
It looks odd that the ItemsSource of your ListView is directly bound to the current DataContext by
ItemsSource="{Binding}"
The DataContext would usually hold a view model object with a collection-type property like
public class Item
{
public bool IsChecked { get; set; }
// other properties like ID, File, Author
}
public class ViewModel
{
public ObservableCollection<Item> Items { get; }
= new ObservableCollection<Item>();
}
and the Binding would be
ItemsSource="{Binding Items}"
Then the view model could have a method that deletes all checked items, like
public void DeleteCheckedItems()
{
var checkedItems = Items.Where(item => item.IsChecked).ToList();
checkedItems.ForEach(item => Items.Remove(item));
}
Note that you usually assign an instance of the view model class to the DataContext of your main view, e.g. in the MainWindow constructor:
private readonly ViewModel viewModel = new ViewModel();
public MainWindow()
{
InitializeComponent();
DataContext = viewModel;
viewModel.Items.Add(new Item { ID = 1, ... });
viewModel.Items.Add(new Item { ID = 2, ... });
}
I have been experiencing problems with WPF ListView (using elements binding), as I tried to initialize it by injecting ItemsSource the list of Disks, and got no visual feedback from the element. I wrote my code using the example supplied here.
Here are the relevant code parts:
Setting the ListView
private void viewDisk_Click(object sender, RoutedEventArgs e)
{
List<DiskDetails> data = new List<DiskDetails>();
foreach(Disk disk in disks)
data.Add(new DiskDetails(disk.GetVolumeHeader().DiskName, disk.GetVolumeHeader().DiskOwner,disk.GetVolumeHeader().ProdDate));
disksList.ItemsSource = data;
}
DiskDetails Class
public class DiskDetails
{
public string diskName { get; set; }
public string diskOwner { get; set; }
public string cDate { get; set; }
public DiskDetails(string dN, string dO,string cD)
{
diskName = dN;
diskOwner = dO;
cDate = cD;
}
}
WPF ListView
<Grid Grid.Column="0">
<ListView x:Name="disksList" VerticalAlignment="Top" Height="250" SelectionChanged="disksList_SelectionChanged">
<ListView.View>
<GridView>
<GridViewColumn Header="Disk Name" Width="108" DisplayMemberBinding="{Binding Name}" />
<GridViewColumn Header="Disk Owner" Width="108" DisplayMemberBinding="{Binding Age}" />
<GridViewColumn Header="Creation Date" Width="108" DisplayMemberBinding="{Binding Mail}" />
</GridView>
</ListView.View>
</ListView>
<Button x:Name="viewDisk" Content="View Disk" Width="90" Height="40" VerticalAlignment="Bottom" Margin="0,0,0,15" Click="viewDisk_Click"/>
</Grid>
Thanks.
Looks like your DisplayMemberBinding wasn't changed from the example code. Try changing the bindings to match the properties of DiskDetails. E.g. DisplayMemberBinding="{Binding Name}" should change to DisplayMemberBinding="{Binding diskName}"
My MVVM WPF application currently has a GridView that binds to a ViewModel property and has the columns defined in the XAML:
<ListView Grid.Row="0" ItemsSource="{Binding GroupedOrders}">
<ListView.View>
<GridView>
<GridViewColumn>
<GridViewColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Item2, Mode=OneWay}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Date" DisplayMemberBinding="{Binding Item1.Date, StringFormat={}{0:dd/MM/yyyy}}" />
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Item1.Name}" />
<!-- lots more -->
</GridView>
</ListView.View>
</ListView>
GroupedOrders is an ObservableCollection of a Tuple of two different item types: an "Order" object and a Boolean that controls whether or not, for this particular view, it is "selected".
However, that "selected" property hasn't been modelled well. It's come to light that each Order needs multiple "selected" properties, depending on the number of dates in the order, which can be between one and five.
To model this in the UI, I need to replace that single Checkbox GridViewColumn with a dynamic construct that creates a similar Checkbox GridviewColumn for each date in the order. So GroupedOrders becomes a Tuple <Order, List<bool>> instead, and there will need to be one column for each bool in the List.
At any given instance, the size of that list will be the same for all the Orders in the grid. But if the user loads new data into the grid, the size of the list will change.
However, I cannot see how to do this in MVVM. Existing solutions seem to be for code-behind where the GridView can be grabbed as an object and manipulated on the fly. The only MVVM solution I've seen to this is to use a Converter to building the entire GridView on the fly, which would seem to be massive overkill for this situation, where there are a lot of columns in the GridView but only a small number need to be dynamic.
Is there another way?
Not sure this is what you expect, but this is what I can think of.
View
<ListView ItemsSource="{Binding Orders}">
<ListView.View>
<GridView>
<GridViewColumn Header="State">
<GridViewColumn.CellTemplate>
<DataTemplate>
<ListView ItemsSource="{Binding States}">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"></StackPanel>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.Resources>
<Style TargetType="GridViewColumnHeader">
<Setter Property="Visibility" Value="Collapsed" />
</Style>
</ListView.Resources>
<ListView.View>
<GridView>
<GridViewColumn>
<GridViewColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Value}" Content="{Binding Text}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="OrderNo" DisplayMemberBinding="{Binding OrderNo}" />
</GridView>
</ListView.View>
</ListView>
Code Behind
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Orders.Add(new Order { OrderNo = "Order001" });
Orders.Add(new Order { OrderNo = "Order002" });
Orders.Add(new Order { OrderNo = "Order003" });
}
private readonly ObservableCollection<Order> _orders = new ObservableCollection<Order>();
public ObservableCollection<Order> Orders
{
get { return _orders; }
}
}
public class Order
{
public Order()
{
States.Add(new State { Text = "Is Paid", Value = false });
States.Add(new State { Text = "Is Delivered", Value = false });
}
public string OrderNo { get; set; }
private readonly ObservableCollection<State> _states = new ObservableCollection<State>();
public ObservableCollection<State> States
{
get { return _states; }
}
}
public class State
{
public string Text { get; set; }
public bool Value { get; set; }
}
Result
I've been trying to practice with data binding and file IO concepts and for that I wrote this simple application that reads a 2 column, 5 row .csv file and displays the contents to a Listview in WPF with the feature that I can change the values of the 2nd column in my Listview (like a 2 way binding).
I have not been able to get any information to display in my window. I only get the column headers that I define in my MainWindow.xaml but none of the data binding is working.
Here is my code for the View Model and reading the file
namespace WpfPreview
{
public class LoadMovieData : BindableObject // My Data Context?
{
public string MovieName { get; set; }
private double year; public double Year { get { return year; } set { year = value; RaisePropertyChanged("Year"); } }
}
class ViewModel : BindableObject
{
private List<LoadMovieData> obsMovies = new List<LoadMovieData>();
public List<LoadMovieData> ObsMovies
{
get { return obsMovies; }
set { obsMovies = value; RaisePropertyChanged("ObsMovies"); }
}
public void ReadFile()
{
string filepath = System.IO.Path.Combine("C:\\Users\\Param\\Desktop", "excel.csv"); // Get filepath
using (var csvReader = new StreamReader(filepath)) // using this filepath
{
csvReader.ReadLine(); // read first line (headers)
csvReader.ReadLine(); // read first line of row data
while (!csvReader.EndOfStream) // while not end of file
{
var words = csvReader.ReadLine().Split(',').ToList(); // read line to list of columns
var x = new LoadMovieData() // new instance of data class
{
MovieName = words[0],
Year = Convert.ToDouble(words[1])
};
ObsMovies.Add(x); // add instance of data class to list variable
}
}
}
}
}
I'm not sure if my terms are correct. I am trying to follow the MVVM pattern. My codebehind for the window is this:
namespace WpfPreview
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new ViewModel();
}
}
}
and here is my XAML part:
<Window x:Class="WpfPreview.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:me="clr-namespace:WpfPreview"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Border Background="White">
<ListView x:Name="MovieListView" ItemsSource="{Binding Path=ObsMovies}" VirtualizingStackPanel.IsVirtualizing="True" Background="Transparent">
<ListView.View>
<GridView>
<GridViewColumn Header="Movie Name">
<GridViewColumn.CellTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding ObsMovies.MovieName}" />
</Grid>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Year" Width="60">
<GridViewColumn.CellTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding ObsMovies.Year}" />
</Grid>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</Border>
</Grid>
I am very new to working with file IO and data binding/data context. I am sure there is an obvious mistake somewhere and that what I'm trying to do could be done in a much easier/less complicated way. Please feel free to give me suggestions to restructure my code.
I generally put my data loading code in my ViewModel constructor. Also, without an access modifier, your ViewModel class is private I believe, so you will not be able to call anything from outside the class. Consider making it public.
It looks like your obsMovies list should be an ObservableCollection. The value of obsMovies implements PropertyChanged notification, but if you add an item to it, the collection does not notify the UI that its collection has changed.
Change this:
private List<LoadMovieData> obsMovies = new List<LoadMovieData>();
public List<LoadMovieData> ObsMovies
{
get { return obsMovies; }
set { obsMovies = value; RaisePropertyChanged("ObsMovies"); }
}
To this:
private ObservableCollection<LoadMovieData> obsMovies = new ObservableCollection<LoadMovieData>();
public ObservableCollection<LoadMovieData> ObsMovies
{
get { return obsMovies; }
set { obsMovies = value; RaisePropertyChanged("ObsMovies"); }
}
You will have to import System.Collections.ObjectModel to make use of it.
Also, it looks like your bindings may not be quite right. Try using the following instead:
<ListView.View>
<GridView>
<GridViewColumn Header="Movie Name">
<GridViewColumn.CellTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding ObsMovies.MovieName}" />
</Grid>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Year" Width="60">
<GridViewColumn.CellTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding ObsMovies.Year}" />
</Grid>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
The above bindings omit the ObsMovies in the TextBlock bindings. Since each rows DataContext is one of the items in the collection, there is no need to have the collection referenced in the binding. Just have the binding path start at the datacontext level (in this case ObsMovies).
Lastly, as promised, a sample implementation of DataGrid:
<DataGrid HorizontalAlignment="Left" VerticalAlignment="Top" ItemsSource="{Binding ObsMovies}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Year}" ClipboardContentBinding="{x:Null}" Header="Year"/>
<DataGridTextColumn Binding="{Binding MovieName}" ClipboardContentBinding="{x:Null}" Header="Movie Name"/>
</DataGrid.Columns>
</DataGrid>
To have textboxes to allow for editing of items, in the listView example, replace the TextBlocks with TextBoxes, and for the DataGrid, specify a DataGridTemplateColumn and put a TextBox in the template:
<DataGridTemplateColumn ClipboardContentBinding="{x:Null}">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Property}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
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>