我需要从我的 ComboBox
获取值es 驻留在 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
.
问题就在这里。我需要获取SelectedIndex
的ComboBox
(所以我会更改当前代码 SelectedIndex="0"
)。如果我的ExternalClass
需要包含那些 SelectedIndex
值,这很容易,因为我已经可以访问它的字段( Variable
和 Value
)。但我需要那些int
值在
public class MainViewModel : ViewModelBase
{
public ObservableCollection<int> SelectedIndices { get; set; }
...
}
或者类似的东西。我制作了一个快速包装类来包含 SelectedIndices
和IVCollection
,但显然这是行不通的,因为 ItemsControl
想要一个ObservableCollection
,不是一个有两个 ObservableCollection
的类s。
我想这里问题的真正核心(我可能是错的,这就是我问的原因)是如何访问 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 等一起使用,但这只是推迟了问题的发生。我需要解决它。或者绕过它。
最佳答案
这就是我的做法,我将为所选值创建一个属性
// within the MainViewModel class
private ExternalClass _selectedObject;
public ExternalClass SelectedObject
{
get { return _selectedObject; }
set
{
_selectedObject= value;
RaisePropertyChanged("SelectedObject");
}
}
然后将ComboBox
中的SelectedItem
绑定(bind)到SelectedObject
属性
<ComboBox ItemsSource="{Binding IVCollection}" SelectedItem="{Binding SelectedObject}" >
<ComboBox.ItemTemplate>
<DataTemplate>
... data template goes here
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
希望这会有所帮助
关于WPF MVVM 访问 ItemsControl DataTemplate 内的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14781401/