Reputation: 678
I would like to make GridView with column header, for example like exampe below (example for one column). My DataTemplate for header contains have more controls (TextBlock and TextBox) and I am not able to figure out how to set binding to access individual controls from template (header). In my example, instead of "aaa" to set value of HColumn1Line2 property.
<ListView Name="PeopleList" ItemsSource="{Binding People}">
<ListView.Resources>
<DataTemplate x:Key="MyHeaderTemplate">
<StackPanel>
<TextBlock Text="{Binding}"/>
<TextBox Text="aaa"></TextBox>
</StackPanel>
</DataTemplate>
</ListView.Resources>
<ListView.View>
<GridView ColumnHeaderTemplate="{StaticResource MyHeaderTemplate}">
<GridViewColumn Header="{Binding HColumn1Line1}" DisplayMemberBinding="{Binding PeopleListItem}"/>
</GridView>
</ListView.View>
</ListView>
//Code
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
PeopleList.DataContext = this;
_people.Add(new Person() { PeopleListItem = "some information" });
HColumn1Line1 = "Header line #1";
HColumn1Line2 = "text instead of aaa";
}
public List<Person> People { get { return _people; } }
List<Person> _people = new List<Person>();
public string HColumn1Line1 { get; set; }
public string HColumn1Line2 { get; set; }
}
public class Person
{
public string PeopleListItem { get; set; }
}
Upvotes: 0
Views: 503
Reputation: 2372
The main problem you have is you are using the MainWindow
instance as DataContext
for the ListView
which is in the MainWindow
Content
this will run you into exceptions such as "Logical tree depth exceeded while traversing the tree.", so you better make your DataContext a seperate object such as the following:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
PeopleList.DataContext = new ViewModel();
}
}
public class ViewModel
{
public List<Person> People { get { return _people; } }
List<Person> _people = new List<Person>();
public string HColumn1Line1 { get; set; } = "Header line #1";
public string HColumn1Line2 { get; set; } = "text instead of aaa";
public ViewModel()
{
_people.Add(new Person() { PeopleListItem = "some information" });
}
}
public class Person
{
public string PeopleListItem { get; set; }
}
Updated XAML:
<ListView Name="PeopleList" ItemsSource="{Binding People}">
<ListView.Resources>
<DataTemplate x:Key="MyHeaderTemplate">
<StackPanel>
<TextBlock Text="{Binding HColumn1Line1}"/>
<TextBox Text="{Binding HColumn1Line2}"></TextBox>
</StackPanel>
</DataTemplate>
</ListView.Resources>
<ListView.View>
<GridView ColumnHeaderTemplate="{StaticResource MyHeaderTemplate}">
<GridViewColumn Header="{Binding}" DisplayMemberBinding="{Binding PeopleListItem}"/>
</GridView>
</ListView.View>
</ListView>
Upvotes: 1