I’ve got some maintenance work to do on some WPF controls, which is something I’m not really familiar with, and I am struggling with some fundamentals in WPF.
I have the following code, which I understand is referred to as “code-behind”:
Class MainWindow
Private _myStrings As New List(Of String)({"one", "two", "three", "four", "five"})
Public Property myStrings As List(Of String)
Get
Return _myStrings
End Get
Set(value As List(Of String))
_myStrings = value
End Set
End Property
End Class
I then have this WPF stuff, which defines a really ugly ComboBox.
<Window x:Class="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>
<ComboBox Margin="0,10,0,0"
x:Name="cboItem"
TabIndex="1"/>
</Grid>
</Window>
Question: All I want to know is how do I correctly create references in the XAML to display the myStrings List in the cboItem ComboBox? Once I know that, I can get around to understanding databinding concepts in detail, but right now, I need someone to explain really basic things for me like “How do I tell XAML where to look for data?”
ComboBoxhas a property calledItemsSourcethat can be set to either a static list of strings, or more commonly, can be bound to some list of objects.WPF objects look for their bindings in their
DataContext. This is a property of every WPF framework element, and will “cascade” down, so setting theDataContextof theWindowmeans that every control on that window will also inherit the sameDataContext. However, they do not have to use the same context. Every control can have its own context set simply by setting itsDataContextproperty.You have defined your list of strings in the window itself (in the code behind). This is not really usual. A more common method used in WPF is to define a ViewModel class that contains all the data your view needs, and then set that as the
DataContext. This is what the MVVM pattern is all about.However, going with your example, there is nothing stopping you from setting your Window’s
DataContextto the Window itself:The
DataContextline tells WPF which object to look at for its bindings, and theItemsSourceline tells the combo which property to use on the context for its list of strings.EDIT: To set the DataContext on the combo you could do: