I've seen plenty of examples of how to add a double-click event for each ListView item, but I can't figure out how to implement it to my code. The best example I found so far is this one in MS docs, but it still doesn't help me handle this :
<ListView Name="listViewItem" ClipToBounds="True" VerticalContentAlignment="Stretch" HorizontalContentAlignment="Stretch" SizeChanged="ListView_SizeChanged" TextOptions.TextHintingMode="Animated" Margin="0,0,117,0">
<ListView.View>
<GridView AllowsColumnReorder="False">
<GridViewColumn Header="Task ID" Width="0">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding TaskID}" TextWrapping="Wrap" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Tast Title" Width="150">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding TaskTitle}" TextWrapping="Wrap" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Task Deadline" Width="275">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding TaskDeadline}" TextWrapping="Wrap" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Task Group" Width="150">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding TaskGroup}" TextWrapping="Wrap" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Task Contact" Width="200">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding TaskContact}" TextWrapping="Wrap" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Task Workers" Width="200">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding TaskWorkers}" TextWrapping="Wrap" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
I have a helpers class that sets values on load event ->
public void GetGridTasks(ref ListView listViewItem)
{
SqlCommand sqlCommandRefresh = new SqlCommand("", dataconnection);
sqlCommandRefresh.CommandText = "SELECT TaskID, TaskTitle, TaskDeadline, TaskGroup, TaskContact, TaskWorkers FROM Tasks";
SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlCommandRefresh);
DataTable dt = new DataTable("Tasks");
sqlAdapter.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
dr["TaskWorkers"] = dr["TaskWorkers"].ToString().Replace("||", ", ");
}
listViewItem.ItemsSource = dt.DefaultView;
}
This is basically TextBlocks inside GridView inside ListView. Can't really wrap my head around fixing this mess.
Just use the MouseDoubleClick Event from the ListView.
Example:
<ListView MouseDoubleClick="ListView_MouseDoubleClick">
//Items here
</ListView>
In your code behind you simply add an event handler for that
void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e){
var item = ((FrameworkElement) e.OriginalSource).DataContext
var myItem = item as *CastToWhateverTypeYouNeed*
if (item != null){
//Here you have your item
}
}
Related
I have a WPF application that uses a ListView with a grid that displays images directly from the web. When the list is populated the images load as expected, but as I scroll down (the list contains around 200 items on average) it starts reusing the items that aren't in view (as it should). However, this causes the images to be released from memory and as a result they get reloaded all over again when the user scrolls back up.
MainWindow.xaml
<ListView Grid.Row="3" ItemsSource="{Binding SearchResults}" Background="{StaticResource PrimaryBackground}" Foreground="{StaticResource PrimaryForeground}"
ui:GridViewSort.AutoSort="True" ui:GridViewSort.ShowSortGlyph="False" IsSynchronizedWithCurrentItem="True" VirtualizingStackPanel.IsVirtualizing="False">
<ListView.View>
<GridView>
<GridViewColumn Width="80">
<GridViewColumn.CellTemplate>
<DataTemplate DataType="{x:Type Foo}">
<Image>
<Image.Source>
<BitmapImage CacheOption="OnDemand" UriSource="{Binding PreviewImageUrl}" />
</Image.Source>
</Image>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Title" DisplayMemberBinding="{Binding Title}" ui:GridViewSort.PropertyName="Title" />
<GridViewColumn Header="Remix" DisplayMemberBinding="{Binding Remix}" ui:GridViewSort.PropertyName="Remix" />
<GridViewColumn Header="Artist" DisplayMemberBinding="{Binding Artist}" ui:GridViewSort.PropertyName="Artist" />
<GridViewColumn Header="Duration" DisplayMemberBinding="{Binding Duration}" ui:GridViewSort.PropertyName="Duration" />
<GridViewColumn Header="BPM" DisplayMemberBinding="{Binding Bpm}" ui:GridViewSort.PropertyName="Bpm" />
<GridViewColumn Header="Year" DisplayMemberBinding="{Binding Date}" ui:GridViewSort.PropertyName="Date" />
<GridViewColumn>
<GridViewColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<StackPanel.Resources>
<Style TargetType="Button">
<Setter Property="Margin" Value="0,0,10,0" />
</Style>
</StackPanel.Resources>
<Button Command="{Binding ElementName=Window, Path=DataContext.Download}" CommandParameter="{Binding}">Download</Button>
<Button Command="{Binding ElementName=Window, Path=DataContext.CopyLink}" CommandParameter="{Binding}">Copy link</Button>
</StackPanel>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
Setting the Image.Source property with a different CacheOption makes no difference. You can also see I disabled virtualization which is bad but it's the only way to have it keep the images in memory. Is there an easy way to stop this from happening while also enabling virtualization?
Add a readonly PreviewImage property to your search results item class that creates and holds the BitmapImage when it is first accessed:
public class SearchResult : INotifyPropertyChanged
{
private Uri previewImageUrl;
public Uri PreviewImageUrl
{
get { return previewImageUrl; }
set
{
previewImageUrl = value;
previewImage = null;
NotifyPropertyChanged(nameof(PreviewImageUrl));
NotifyPropertyChanged(nameof(PreviewImage));
}
}
private ImageSource previewImage;
public ImageSource PreviewImage
{
get
{
if (previewImage == null && previewImageUrl != null)
{
previewImage = new BitmapImage(previewImageUrl);
}
return previewImage;
}
}
...
}
and bind to it like this:
<GridViewColumn.CellTemplate>
<DataTemplate>
<Image Source="{Binding PreviewImage}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
Try this:
<Image
HorizontalOptions="CenterAndExpand"
VerticalOptions ="CenterAndExpand">
<Image.Source>
<UriImageSource Uri="{Binding Image}"
CacheValidity="14"
CachingEnabled="true"/>
</Image.Source>
</Image>
I want to get all the items in a listview that the checkbox has checked.
<ListView x:Name="lvwStudent" IsSynchronizedWithCurrentItem="True" SelectionMode="Multiple" HorizontalAlignment="Stretch" HorizontalContentAlignment="Center" VerticalContentAlignment="Center">
<ListView.View>
<GridView>
<GridViewColumn Width="50">
<GridViewColumn.CellTemplate>
<DataTemplate>
<CheckBox x:Name="cboxSelected" Content ="{Binding ID}" Width="20" Height="20" BorderBrush="#FF0C6161" HorizontalAlignment="Center" HorizontalContentAlignment="Center" Tag="{Binding ID}" IsChecked="{Binding IsChecked}" Checked="cboxSelected_Checked_1" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="NO." Width="53">
<GridViewColumn.CellTemplate>
<DataTemplate >
<Label Content ="{Binding ID}" FontSize="14" HorizontalContentAlignment="Center"></Label>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="STUDENT NAME" Width="auto">
<GridViewColumn.CellTemplate>
<DataTemplate>
<Label Content ="{Binding STUDENT_NAME}" FontSize="14" HorizontalContentAlignment="Center"></Label>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
when I click the select button I want to get all selected ID and store in an array.
private void btnSelect_Click(object sender, RoutedEventArgs e)
{
int[] selectedId;
if(lvwMachine.SelectedItems.Count > 0)
{
foreach(..... )
{
//add all selected id in array selectedId
}
}
List<Student>StudentList = new Students().getStudent();
List<ListViewItem> ITEM = new List<ListViewItem>();
foreach (var s in StudentList)
{
ListViewItem OneItem = new ListViewItem();
OneItem.Content = new Student()
{ID = s.ID, STUDENT_NAME = s.name};
ITEM.Add(OneItem);
lvwMachine.ItemsSource = ITEM;
}
You can try this:
lvwMachine.ItemsSource.Where(element => element.IsChecked).ToArray();
How do I get my listview to do both grouping and filtering because I can only get it to do one of the thing at once. I had tried almost everything I could but none of it worked. when i remove
public string SelectedParam { get { return _selectedParam; } set { _selectedParam = value; OnPropertyChanged("SelectedParam");
if (_selectedParam == "Krydsmål") { BindData(); } else { hjuldata.ItemsSource = FilterKategori().Tables[0].DefaultView; ; } } }
then the grouping works but the filtering doesn't
i wonder if i can use the sql for filling instead for both filling and filtering and then get the listview to do the filtering like you can do with manualy added items
My combobox for filtering:
<ComboBox x:Name="Krydsmålbox" Foreground="#FFEAEAEA" Background="#FF303030" FontSize="12"
Style="{StaticResource ComboBoxTest2}" ItemTemplate="{StaticResource cmbTemplate2}"
ItemsSource="{Binding}" SelectedValuePath="Krydsmålene"
SelectedValue = "{Binding SelectedParam, RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type Window}},UpdateSourceTrigger=PropertyChanged}" BorderBrush="#FF303030" Height="40" DockPanel.Dock="Top" Margin="586,42,379,0"/>
Listview
<ListView x:Name="hjuldata" BorderBrush="#FF303030" Foreground="#FF00FB0B" ScrollViewer.VerticalScrollBarVisibility="Auto" ScrollViewer.HorizontalScrollBarVisibility="Auto" Background="#FF303030" ItemsSource="{Binding}" Margin="-160,242,11,22" Grid.ColumnSpan="6" Grid.Row="3" Style="{DynamicResource ListViewStyle2}" DockPanel.Dock="Bottom" Height="576">
<ListView.View>
<GridView>
<GridView.ColumnHeaderContainerStyle>
<Style TargetType="{x:Type GridViewColumnHeader}">
<Setter Property="Background" Value="Black" />
<Setter Property="Foreground" Value="#FFEAEAEA"/>
<Setter Property="FontWeight" Value="Bold" />
</Style>
</GridView.ColumnHeaderContainerStyle>
<GridViewColumn Header="" >
<GridViewColumn.CellTemplate>
<DataTemplate>
<Image Source="{Binding Billed, Converter={StaticResource nullImageConverter}}" Width="20" Height="20" Stretch="Fill" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="0,0,15,0"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Model" Width="140" >
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock x:Name="Txt" Text="{Binding Model}" Foreground="#FF00FB0B" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Årgang" Width="100">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock x:Name="Txt" Text="{Binding Årgang}" Foreground="#FF00FB0B" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Motor Type" Width="150" >
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock x:Name="Txt" Text="{Binding [Motor Type]}" Foreground="#FF00FB0B" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn>
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock x:Name="Txt" Text="{Binding Krydsmålet}" Foreground="#FF00FB0B" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn>
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock x:Name="Txt" Text="{Binding Centerhul}" Foreground="#FF00FB0B" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="ET" Width="auto">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock x:Name="Txt" Text="{Binding ET}" Foreground="#FF00FB0B" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Bolter" Width="100">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock x:Name="Txt" Text="{Binding Bolter}" Foreground="#FF00FB0B" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Dæk" Width="300">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock x:Name="Txt" Text="{Binding Dæk}" Foreground="#FF00FB0B" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Fælge" Width="200">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock x:Name="Txt" Text="{Binding Fælge}" Foreground="#FF00FB0B" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
grouping style
<ListView.GroupStyle>
<GroupStyle>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Expander IsExpanded="False" BorderBrush="#FFEAEAEA" BorderThickness="0,0,0,1" >
<Expander.Header>
<StackPanel Orientation="Horizontal" DataContext="{Binding Items}">
<Image Source="{Binding Billed, Converter={StaticResource nullImageConverter}}" Width="20" Height="20" Stretch="Fill" VerticalAlignment="Center" Margin="0,0,15,0"/>
<TextBlock Text="{Binding Mærke}" FontWeight="Bold" Foreground="#FFEAEAEA" FontSize="22" VerticalAlignment="Bottom" />
<TextBlock Text="{Binding Krydsmålene}" FontWeight="Bold" Foreground="#FFFBFB00" FontSize="22" VerticalAlignment="Bottom" Margin="0,0,150,0" TextAlignment="Center" />
</StackPanel>
</Expander.Header>
<ItemsPresenter />
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</ListView.GroupStyle>
</ListView>
CS:
public partial class MainWindow : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _selectedParam;
public MainWindow()
{
InitializeComponent();
BindData();
ICollectionView dataView = CollectionViewSource.GetDefaultView(hjuldata.ItemsSource);
dataView.GroupDescriptions.Add(new PropertyGroupDescription("Mærke"));
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public string SelectedParam { get { return _selectedParam; } set { _selectedParam = value; OnPropertyChanged("SelectedParam");
if (_selectedParam == "Krydsmål") { BindData(); } else { hjuldata.ItemsSource = FilterKategori().Tables[0].DefaultView; ; } } }
private void BindData()
{
hjuldata.ItemsSource = Kategori().Tables[0].DefaultView;
}
public DataSet Kategori()
{
Data = #"Select ps.Mærket AS Mærke, P.DataID, P.Billed, P.Model, P.Årgang, P.[Motor Type], P.Krydsmålet, P.Centerhul, P.ET,P.Bolter, P.Dæk, P.Fælge ,PS.Krydsmålene from Data.Hjuldata P inner join Data.Mærke PS on P.MærkeID = PS.MærkeID ORDER BY ps.Mærket";
//SQL statement to fetch entries from Hjuldata
DataSet dsdata = new DataSet();
//Open SQL Connection
using (conn = new SqlConnection(connStrings))
{
conn.Open();
//Initialize command object
using (cmd = new SqlCommand(Data, conn))
{
SqlDataAdapter adapters = new SqlDataAdapter(cmd);
//Fill the result set
adapters.Fill(dsdata);
conn.Close();
}
}
return dsdata;
}
public DataSet FilterKategori()
{
Data = #"Select ps.Mærket AS Mærke, P.DataID, P.Billed, P.Model, P.Årgang, P.[Motor Type], P.Krydsmålet, P.Centerhul, P.ET,P.Bolter, P.Dæk, P.Fælge ,PS.Krydsmålene from Data.Hjuldata P inner join Data.Mærke PS on P.MærkeID = PS.MærkeID WHERE Krydsmålet = #param1";
//SQL statement to fetch entries from products
DataSet dsdata = new DataSet();
//Open SQL Connection
using (conn = new SqlConnection(connStrings))
{
conn.Open();
//Initialize command object
using (cmd = new SqlCommand(Data, conn))
{
cmd.Parameters.AddWithValue("#param1", SelectedParam);
SqlDataAdapter adapters = new SqlDataAdapter(cmd);
//Fill the result set
adapters.Fill(dsdata);
conn.Close();
}
}
return dsdata;
}
Can somebody help me with this please?
I think your problem is that you are using the ADO.NET data view abstraction rather than the WPF data view abstraction which should be easier to use. In WPF when you bind a collection or DataTable to an ItemsControl a data view object is created that basically serves as a layer over your collection or DataTable. By doing this you can potentially have the same collection bound to multiple ItemsControls but have different "views" of that data by having different filtering and grouping for the two distinct data views that are created for that same collection.
In your case you are binding to a DataTable which is messier than binding just to a collection that implements IList. For DataTable there is a DataView class that is part of ADO.NET that your WPF data view will basically serve as a layer over and this DataView is more limited in functionality (this ADO.NET DataView is what you are using in your code currently).
Either way, to get the WPF data view you just need to ask the ItemsSource for it like so:
ICollectionView dataView = CollectionViewSource.GetDefaultView(myListView.ItemsSource);
Now you will want to cast the ICollectionView to something more useful for setting the filter and grouping. In your case you have a DataTable so you will want to cast that to a BindingListCollectionView. Unfortunately this is more limited than the data view you would get for an IList (which is a ListCollectionView), but you have a DataTable so we will just roll with it for now (I always go with IList so I have never actually implemented a DataTable binding in production before).
The BindingListCollectionView doesn't have an operational Filter property so you have to use its CustomFilter property to specify the partial SQL that you want to use to filter your collection (basically what you would have put in a WHERE clause). As far as grouping goes I haven't ever used it on a DataTable binding but I would hope it just works by updating GroupDescriptions on the data view.
So basically in summary I would grab the WPF data view abstraction rather than the ADO.NET data view abstraction that you are currently using and set the filter and grouping on that. Also I would recommend just bringing in your data as an IList or else converting it to an IList since those are easier to work with in WPF.
i think this is something you should read
How to: Group, Sort, and Filter Data in the DataGrid Control
i had tested that one and it works with your datastructure and you dont have to do anything with your filtering only change out the grouping part and colectionview
I'm Using WPF.
I have ListView with TextBox column and two checkboxs columns.
I want to edit the TextBox text by double click or something else.
What is the simple way to do that?
...
<GridViewColumn Header="Name" DisplayMemberBinding={Binding Path=fullName}" Width=500>
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBox Name="txtName"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
...
Here is a sample way of doing this...
public partial class MainWindow : Window
{
public List<string> Items { get; set; }
public MainWindow()
{
InitializeComponent();
Items = new List<string>();
LoadItems();
DataContext = this;
}
private void txtName_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
TextBox currentTextBox = (TextBox)sender;
if (currentTextBox.IsReadOnly)
currentTextBox.IsReadOnly = false;
else
currentTextBox.IsReadOnly = true;
}
private void LoadItems()
{
Items.Add("Coffee");
Items.Add("Sugar");
Items.Add("Cream");
}
}
<Grid>
<ListView ItemsSource="{Binding Items}">
<ListView.View>
<GridView>
<GridViewColumn Header="Name">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBox Name="txtName" Text="{Binding Mode=OneTime}" IsReadOnly="True" MouseDoubleClick="txtName_MouseDoubleClick" Width="100"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</Grid>
Here is an example I have from an application that I wrote. The column JobName was to be user editable. This example allows the column to be editable and also gets rid of the border and lets the background blend into the row so it doesn't appear to have a text box in it.
Those can be edited out (BorderThickness="0" Background="Transparent").
My example binds to an MVVM ViewModel property called JobName and is set to be "TwoWay" so that changes to the view model will also reflect on the UI.
<ListView x:Name="lvJobs" HorizontalAlignment="Left" Height="628" Margin="30,62,0,0" ItemsSource="{Binding Jobs}"
SelectedItem="{Binding SelectedJob, Mode=TwoWay}" VerticalAlignment="Top" Width="335">
<ListView.View>
<GridView>
<GridViewColumn Header="Active" Width="50">
<GridViewColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsActive, Mode=TwoWay}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Job Name" Width="150">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding JobName, Mode=TwoWay}" BorderThickness="0" Background="Transparent"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn DisplayMemberBinding="{Binding User}" Header="User" Width="125"/>
</GridView>
</ListView.View>
</ListView>
I have a simple (I think) app that reads an SQL database into variables in my program, and I then need to update a gridview defined in XAML with the data I read. I'm constrained to code for .NET 3.5. All the searching I've done on the books I have on XAML, MS .NET help and elsewhere on the Web shows countless examples of doing this from ASP.NET, but none from a C#-XAML combination. I've found doing simple things in XAML ++much++ more difficult and involved than doing the same thing in Winforms, and I'm just not getting this. In particular, data binding seems to me to be a black art. Can someone please look at my XAML and tell me what I need to do or change to populate this control from my C# code-behind?
Here is my XAML:
<Window x:Class="UCCResourceManager.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="UCC Resource Mangler" Height="350" Width="700">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="250"/>
<RowDefinition />
</Grid.RowDefinitions>
<ListView Name="grdResource"
ItemsSource="{Binding}"
Grid.Row="0">
<ListView.View>
<GridView AllowsColumnReorder="false"
ColumnHeaderToolTip="UCC Resource Table">
<GridViewColumn DisplayMemberBinding="{Binding Path=ID}"
Header="ID"
Width="50"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=LocationID}"
Header="LocationID"
Width="75"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=Type}"
Header="Type"
Width="50"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=Name}"
Header="Name"
Width="200"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=Enabled}"
Header="Enabled"
Width="50"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=Flags}"
Header="Flags"
Width="50"/>
</GridView>
</ListView.View>
</ListView>
<Button Name="btnOK"
Content="OK"
Grid.Row="1"
Width="100"
Height="20
" Click="btnOK_Click" />
</Grid>
</Window>
I recommand to use MVVM. There you have a ViewModel class where you can have your properties to bind to.
public class MainWindowViewModel
{
#region Constructor
public MainWindowViewModel()
{
YourGridList = new ObservableCollection<GridElement>();
var el = new GridElement
{
Element1 = "element 1",
Element2 = "element 2",
Element3 = "element 3"
};
YourGridList.Add(el);
}
#endregion
#region Private members
private ObservableCollection<GridElement> _yourGridList;
private ICommand _addElementCommand;
#endregion
#region Public properties
public ObservableCollection<GridElement> YourGridList
{
get
{
return _yourGridList;
}
set
{
_yourGridList = value;
}
}
#endregion
#region Commands
public ICommand AddElementCommand
{
get { return _addElementCommand ?? (_addElementCommand = new DelegateCommand(AddElement)); }
}
#endregion
#region Private Methods
private void AddElement()
{
var el = new GridElement
{
Element1 = "NewEl1",
Element2 = "NewEl2",
Element3 = "NewEl3"
};
YourGridList.Add(el);
}
#endregion
Then, you can use in the xaml.cs file this class as DataContext.
public MainWindow()
{
InitializeComponent();
DataContext = new MainWindowViewModel();
}
And from the xaml file you can have your ListView ItemsSource populated from the "YourGridList" property from the ViewModel.
<Window x:Class="WpfApplication6.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="35"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button Content="Add element" Command="{Binding AddElementCommand}" Grid.Row="0"/>
<ListView Grid.Row="1"
Margin="10"
ItemsSource="{Binding YourGridList, UpdateSourceTrigger=PropertyChanged}"
MaxHeight="300">
<ListView.View>
<GridView>
<GridView.Columns>
<GridViewColumn Width="Auto">
<GridViewColumn.Header>
<GridViewColumnHeader Content="Element 1" HorizontalContentAlignment="Left" />
</GridViewColumn.Header>
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Element1}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Width="Auto">
<GridViewColumn.Header>
<GridViewColumnHeader Content="Element 2" HorizontalContentAlignment="Left" />
</GridViewColumn.Header>
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Element2}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Width="Auto" >
<GridViewColumn.Header>
<GridViewColumnHeader Content="Element 3" HorizontalContentAlignment="Left" />
</GridViewColumn.Header>
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Element3}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView.Columns>
</GridView>
</ListView.View>
</ListView>
</Grid>
</Grid>
This should work for updating your ListView and have a clear decoupling between the code and the xaml part.