请看下面的图片:
列表框中只有三个项目显示在上面的图像中,但根据用户的选择,它可以是任意数量的项目。
现在,正如您在上图中所看到的,每个项目都有两个组合框。现在我希望在我的viewModel中有selectedItem
或SelectedValue
,我应该可以从中获取用户的选择。现在我不知道如何绑定这些组合框以获得用户的选择。
假设我只有一个项而不是列表然后我会声明一个int类型的属性,这样我就可以轻松获得selectedValue但是对于列表我非常困惑。有人能指出我正确的方向吗?
答案 0 :(得分:1)
首先,假设您要绑定组合框的类是
public class UnitSource :INotifyPropertyChanged
{
public IEnumerable Units
{
get { return new[] { "Test Unit", "Alternate Unit" }; }
}
string _selectedComboItem1;
public string SelectedComboItem1
{
get
{
return _selectedComboItem1;
}
set
{
if (_selectedComboItem1 == value)
return;
_selectedComboItem1 = value;
OnPropertyChanged();
}
}
string _selectedComboItem2;
public string SelectedComboItem2
{
get
{
return _selectedComboItem2;
}
set
{
if (_selectedComboItem2 == value)
return;
_selectedComboItem2 = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
然后在您的视图模型中,您将拥有UnitSource
的ObservableCollection,如下所示
public ObservableCollection<UnitSource> MuchoUnitSources
{
get; set;
}
要使所选的ListBoxItem在ViewModel中具有此功能
private UnitSource _selectedUnitSource;
public UnitSource SelectedUnitSource
{
get
{
return _selectedUnitSource;
}
set
{
if (_selectedUnitSource == value)
return;
_selectedUnitSource = value;
OnPropertyChanged();
}
}
让我们假设它是如此初始化
MuchoUnitSources = new ObservableCollection<UnitSource>(new []{ new UnitSource(),new UnitSource() });
在您的视图中,您的列表框应如下所示
<ListBox Name ="TestList1" ItemsSource="{Binding MuchoUnitSources}" SelectedItem="{Binding SelectedUnitSource}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<ComboBox SelectedItem="{Binding SelectedComboItem1}" ItemsSource="{Binding Units}" />
<ComboBox SelectedItem="{Binding SelectedComboItem2}" ItemsSource="{Binding Units}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
现在,无论何时从任何组合框中选择一个项目,它们都会更新绑定的对象。