我有我想要做的独特行为。Silverlight SelectedIndex not Databinding Correctly
我有一个combobox是数据绑定到视图模型项目列表。第一项是“[选择项目]”。预期的行为是,当用户选择一个项目时,我会做一些事情,然后将索引重置回第一个项目。
这是有效的,除了如果你想选择第三项,连续2次。这里是代码: ItemViewModel:
// 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; }
}
视图模型:(我的所有属性调用适当的设置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将不火,除非我选择别的东西。
我不太确定如何让它起作用。任何帮助将不胜感激。
就是这样。谢谢。实际的意图是选择代码片段并自动插入到文本主体中,保存点击后不需要额外的按钮来执行插入操作。再次感谢。 – Andre