In code I can do "listView.ItemsSource = testlist" but how do I do the same in XAML?
My Window class has:
List<string> testlist = new List<string>();
In the constructor I have:
listView.ItemsSource = testlist;
The XAML is:
<ListView x:Name="listView" Margin="0" />
If I add to testlist then I get the list, but I just cannot figure out what the syntax is to assign the ItemsSource in XAML. In other words, I want to know how to assign the ItemsSource in XAML instead of in code.
It is my impression that XAML must make everything complicated.
I am sure there is an answer already, but I can't find any. I have looked at many questions and articles. All the questions and articles are about more complicated requirements or are only partial and don't show all the pieces even when the sample is as small as this.
What I really want to do is to create a template for the ListView with a TextBox in it but I want to at least be able to do it without even that.
Clarification: I am trying to do all the binding in code and with an existing class such as List without creating an additional class just to hold an array of strings, if that is possible. I want to know what the simplest solution would be.
The following is the complete MainWindow code:
public partial class MainWindow : Window
{
List<string> testlist = new List<string>();
public MainWindow()
{
InitializeComponent();
testlist.Add("One");
testlist.Add("Two");
testlist.Add("Three");
}
}
The following is the XAML except the Window tag:
<Grid>
<ListView x:Name="listView" Margin="0" />
</Grid>
You can bind to the property in code-behind by specifying the RelativeSource on the binding. check this.
RelativeSource={RelativeSource Self}
In your case, you can create a property testlist in the code behind and the following xaml.
Code-behind
public ObservableCollection<string> testlist { get; set; } = new ObservableCollection<string>();
XAML
<Window ...
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid >
<ListView ItemsSource="{Binding testlist}"/>
</Grid>
</Window>