【发布时间】:2013-02-08 21:09:36
【问题描述】:
我需要从我的ComboBoxes 中获取值,这些值位于ObservableCollection 中,并被ItemsControl 迭代。而且我需要将它们存储在一个单独的数据结构中,至少我认为是这样。听起来很简单?我希望是的,我整天都在坚持。
这是我的 XAML:
<Window.Resources>
<Style x:Key="IVCell" TargetType="{x:Type ItemsControl}">
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Variable.Name}"/>
<ComboBox x:Name="IVValues" ItemsSource="{Binding Values}"
SelectedIndex="0"/>
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
...
<ItemsControl Name="IndependentVariables" Style="{StaticResource IVCell}" ItemsSource="{Binding IVCollection}"/>
IVCollection 在此处定义,在我的 ViewModel 中:
public class MainViewModel : ViewModelBase
{
public ObservableCollection<ExternalClass> IVCollection { get; set; }
...
}
在你问ExternalClass 是什么之前,要知道那是包含Variable 和Values 的内容。
这就是问题所在。我需要获得ComboBox 的SelectedIndex(所以我将更改当前代码SelectedIndex="0")。如果我的ExternalClass 是包含那些SelectedIndex 值所需的,那将很容易,因为我已经可以访问它的字段(Variable 和Value)。但我需要那些int 值
public class MainViewModel : ViewModelBase
{
public ObservableCollection<int> SelectedIndices { get; set; }
...
}
或类似的东西。我制作了一个包含SelectedIndices 和IVCollection 的快速包装类,但显然这行不通,因为ItemsControl 想要一个ObservableCollection,而不是一个有两个ObservableCollections 的类。
我猜这里问题的真正实质(我可能是错的,这就是我要问的原因)是我如何访问Style/DataTemplate 范围之外的属性我是目前在(例如IVCell)?我可以在代码隐藏中毫无问题地做到这一点,就像这样,
private void IVValues_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
for (var i = 0; i < IndependentVariables.Items.Count; i++)
{
var uiElement = IndependentVariables.ItemContainerGenerator.ContainerFromIndex(i);
var cBox = FindVisualChild<ComboBox>(uiElement); //Homebrew method
//cBox.SelectedIndex
}
}
但我再次尝试保持对 MVVM 友好。我什至尝试过将事件命令与 MVVM Light 等一起使用,但这只会推迟问题。我需要解决它。或者绕过它。
【问题讨论】:
-
因此,如果您设法将每个 ComboBox 的选定索引值绑定到您的 SelectedIndices 集合,您将如何跟踪哪个值来自哪个 ComboBox / ExternalClass?听起来 IVCollection 中项目的长度可能是固定的,因此您的意图是使用 SelectedIndices 中值的索引,但我并不完全清楚。
-
您需要
ExternalClass中的另一个或两个属性来绑定 ComboBox 的 SelectedItem 和/或 SelectedIndex 以跟踪选择了哪些项目。
标签: wpf mvvm datatemplate itemscontrol