【发布时间】:2011-11-13 23:56:10
【问题描述】:
我有自己想做的独特行为。
我有一个数据绑定到视图模型项目列表的组合框。第一项是“[选择项目]”。预期的行为是,当用户选择一个项目时,我会做一些事情,然后将索引重置回第一个项目。
这行得通,除了如果你想选择第 3 项,连续 2 次。这是代码: 项目视图模型:
// NOTE, I have all the INotify goo actually implemented, this is the shorthand
// without goo to make it more readable.
public class ItemViewModel : INotifyPropertyChanged
{
public string Caption { get; set; }
public string Test { get; set; }
}
ViewModel:(我所有的属性在集合中酌情调用 OnPropertyChanged)
public class ViewModel : INotifyPropertyChanged
{
public ObservableCollection<ItemViewModel> ChildItems { get; set; }
public int SelectedChildIndex { get; set; }
public string DebugOutText { get; set; }
public ViewModel()
{
ChildItems = new ObservableCollection<ItemViewModel>();
SelectedChildIndex = -1;
DebugOutText = string.Empty;
}
public void LoadChildItems()
{
ChildItems.Add(new ItemViewModel { Caption = "[ Select Item ]" });
ChildItems.Add(new ItemViewModel { Caption = "One", Test = "Item 1" });
ChildItems.Add(new ItemViewModel { Caption = "Two", Test = "Item 2" });
ChildItems.Add(new ItemViewModel { Caption = "Three", Test = "Item 3" });
SelectedChildIndex = 0;
}
private void OnPropertyChanged(string propName)
{
if (propName == "SelectedChildIndex") { this.OnSelectedChildIndexChanged(); }
if (this.PropertyChanged != null)
{ this.PropertyChanged(this, new PropertyChangedEventArgs(propName)); }
}
public void OnSelectedChildIndexChanged()
{
if (SelectedChildIndex <= 0) return;
DebugOutText += "\r\n" + ChildItems[SelectedChildIndex].Test;
SelectedChildIndex = 0; // <- BIG ISSUE HERE
}
}
现在我的 xaml:
<StackPanel HorizontalAlignment="Left">
<ComboBox Width="200" x:Name="combo"
ItemsSource="{Binding Path=ChildItems}"
SelectedIndex="{Binding Path=SelectedChildIndex, Mode=TwoWay}"
DisplayMemberPath="Caption" />
<TextBlock Text="{Binding Path=DebugOutText}"/>
</StackPanel>
我的应用程序终于启动了:
var vm = new ViewModel();
vm.LoadChildItems();
this.RootVisual = new MainPage { DataContext = vm };
回购步骤是:
- 运行它
- 选择组合并单击/选择“两个”。
- 现在,单击组合。视觉样式将显示“Two”被突出显示(“[ Select Item ]”应该被突出显示)。如果您单击/选择“二”,则不会发生任何事情。
我已经放了一些跟踪代码,组合的 SelectedIndex 为 0,ViewModel.SelectedChildIndex 为 0,但组合的 SelectionChanged 不会触发,除非我选择其他内容。
我不确定如何让它工作。任何帮助将不胜感激。
【问题讨论】:
标签: silverlight data-binding silverlight-4.0 mvvm combobox