我是WPF的新手,我一直在尝试使用MVVM模式。 我试图将类的2个属性绑定到ComboBox和TextBox。
ComboBox工作正常,我有两个项目,但我不确定如何将TextBox绑定到选定的项目'详细信息'属性。因此,当更改ComboBox所选项目时,TextBox也将更新。
任何帮助都将不胜感激。
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
答案 0 :(得分:1)
您可以将Name命名为Combo并绑定到以下内容:
<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"/>