Nathan Nathan - 6 months ago 43
Vb.net Question

MVVM Databinding a list

I'm new to WPF and I have been trying to use the MVVM pattern.
I am trying to bind 2 properties of a class to a ComboBox and a TextBox.

The ComboBox works fine and I have 2 items in there, but I am unsure how to bind the TextBox to the selected items 'Details' property. So when the ComboBox selected item is changed the TextBox will update also.

Any help would be appreciated.

MainView.xaml

<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 ItemsSource="{Binding Scenarios}" DisplayMemberPath="Name" SelectedValuePath="Name" SelectedValue="{Binding Name}" HorizontalAlignment="Right" Width="95" Height="23" VerticalAlignment="Bottom" Margin="0,0,412,287" />

<TextBox HorizontalAlignment="Left" Height="23" Margin="119,10,0,0" TextWrapping="Wrap" Text="{Binding Details}" VerticalAlignment="Top" Width="120"/>

</Grid>
</Window>


MainView.xaml.vb

Class MainWindow
Sub New()

' This call is required by the designer.
InitializeComponent()

' Add any initialization after the InitializeComponent() call.
Me.DataContext = New MainViewModel()
End Sub
End Class


MainViewModel.vb

Imports System.Collections.ObjectModel

Public Class MainViewModel
Public Property Scenarios As ObservableCollection(Of Scenario)

Sub New()
Dim scenarioList As New List(Of Scenario)

Dim scenario1 As New Scenario
scenario1.Name = "Test1"
scenario1.Details = "Test scenario 1"
scenarioList.Add(scenario1)

Dim scenario2 As New Scenario
scenario2.Name = "Test2"
scenario2.Details = "Test scenario 2"
scenarioList.Add(scenario2)

Scenarios = New ObservableCollection(Of Scenario)(scenarioList)
End Sub
End Class


Scenario.vb

Public Class Scenario
Public Property Name As String
Public Property Details As String

End Class

Answer

You can give Name to Combo and bind to like below:

<ComboBox x:Name="myCombo" ItemsSource="{Binding Scenarios}" DisplayMemberPath="Name" SelectedValuePath="Name" SelectedValue="{Binding Name}" HorizontalAlignment="Right" Width="95" Height="23" VerticalAlignment="Bottom" Margin="0,0,412,287" />

<TextBox HorizontalAlignment="Left" Height="23" Margin="119,10,0,0" TextWrapping="Wrap" Text="{Binding SelectedItem.Details, ElementName=myCombo}" VerticalAlignment="Top" Width="120"/>