【发布时间】:2016-05-04 21:09:53
【问题描述】:
我有静态组合框项目。我的 XAML 如下所示:
<ComboBox x:Name="comboBox" SelectedItem="{Binding MySelectedItem}" HorizontalAlignment="Left" Margin="58,7,0,0" VerticalAlignment="Top" Width="120">
<ComboBoxItem Name="cbi1">Item 1</ComboBoxItem>
<ComboBoxItem Name="cbi2">Item 2</ComboBoxItem>
<ComboBoxItem Name="cbi3">Item 3</ComboBoxItem>
</ComboBox>
模型视图:
// How to set initial value here or in constructor?
private ComboBoxItem _mySelectedItem;
public ComboBoxItem MySelectedItem
{
get
{
return _mySelectedItem;
}
set
{
Console.WriteLine("Value = {0}", (value as ComboBoxItem).Name);
}
}
如何设置具有Name 的组合框的选定项?从持久存储读取后,我想在 MV 构造函数中设置选定项。
【问题讨论】:
-
你不能那样做。 ComboBoxItem 是一种引用类型,在您的 ViewModel 中您将无法获取 ComboBox 项的引用
-
否则,您可以使用 SelectedIndex 代替 SelectedItem
-
SelectedIndex 有效,但这不是最好的解决方案。据我了解,要使 SelectedItem 工作,我必须从 ViewModel 创建和填充 ComboBox 项目?如果您知道如何,我们将不胜感激。
-
您必须在 ViewModel 上创建它。我会回答的
标签: c# wpf combobox mvvm-light