Reputation: 147
I want to add some items to a listview that is a gridview.
I want to do it through code without implementing the binding option, Simply adding values to set of cells of some sort.
I know it's not the WPF-way but I need this done urgently and I can't seem to find the answer I'm looking for.
I looked at multibind, converters and regular binding but it just won't give me the answer I need for now.
Is it even possible?
If so how can I do it?
Upvotes: 0
Views: 4556
Reputation: 426
You need index bindings like "[0]".
<Grid>
<ListView x:Name="lv" />
</Grid>
lv.Items.Clear();
var gv = new GridView();
lv.View = gv;
var columns = new List<string> { "col1", "col2" };
for(int index = 0; index < columns.Count; index++)
{
gv.Columns.Add(new GridViewColumn
{
Header = columns[index],
DisplayMemberBinding = new Binding("[" + index.ToString() + "]")
});
}
// Populate list
var row1 = new List<string> { "(1, 1)", "(2, 1)" };
var row2 = new List<string> { "(1, 2)", "(2, 2)" };
lv.Items.Add(row1);
lv.Items.Add(row2);
Upvotes: 1
Reputation: 31656
Don't get hung up on whether to load or not load controls in codebehind. I have worked major Silverlight projects where it was a mixture of both operations.
public MainWindow()
{
InitializeComponent();
lvPrimary.ItemsSource = new List<string> { "Alpha", "Beta", "Gamma" };
}
With Xaml looking like this:
<Window x:Class="WPFStackOverflow.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>
<ListView Name="lvPrimary" Width="200"/>
</Grid>
</Window>
Upvotes: 0
Reputation: 7573
Can you use a DataGrid
instead of a ListView
? Then you can set AutoGenerateColumns
to true (is true by default even).
<DataGrid x:Name="myDataGrid" AutoGenerateColumns="True"/>
Then in the code behind do something like this:
myDataGrid.Items = new List<MyDataType>();
foreach(var item in itemsToAdd){
myDataGrid.Items.Add(item);
}
or shorter:
myDataGrid.ItemsSource = myListOfItems;
Upvotes: 1