Jos*_*ose 7 wpf combobox selecteditem mvvm
好的,我一直在与WPF合作,但我需要一些帮助.
我有一个ComboBox
如下:
<TabControl>
<TabItem Header="1">
<ComboBox ItemsSource="{Binding MyList}" SelectedItem="{Binding MyListSelection}"/>
</TabItem>
<TabItem Header="2"/>
</TabControl>
Run Code Online (Sandbox Code Playgroud)
每当我离开标签1然后回到它时,选择就会被移除.我认为这样做的原因是控件在超出范围然后重新进入时会被销毁.但是在过程中,SelectedItem变为null,这不是用户想要的,因为UI是一个事件生命周期.
所以我想知道最佳路线是什么?我正在使用MVVM构建这个应用程序,所以我可以忽略我的ViewModel中MyListSelection属性的set调用,但是我在整个地方都有ComboBox,并且不喜欢修改我的ViewModel,因为我认为它是WPF的一个bug.
我可以子类化WPF ComboBox,但是没有SelectedItemChanging事件我只能在SelectedItem更改时添加处理程序.
有任何想法吗?
更新:
好吧,在我的头撞墙后,我发现为什么我的问题无法复制.如果列表项类型由于某种原因是一个类,则由WPF将SelectedItem设置为null,但如果它是值类型则不会.
这是我的测试类(VMBase只是一个实现INotifyPropertyChanged的抽象类):
public class TestListViewModel : VMBase
{
public TestListViewModel()
{
TestList = new List<TestViewModel>();
for (int i = 0; i < 10; i++)
{
TestList.Add(new TestViewModel(i.ToString()));
}
}
public List<TestViewModel> TestList { get; set; }
TestViewModel _SelectedTest;
public TestViewModel SelectedTest
{
get { return _SelectedTest; }
set
{
_SelectedTest = value;
OnPropertyChanged("SelectedTest");
}
}
}
public class TestViewModel : VMBase
{
public string Name {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
因此,当我将TestList更改为int类型并在选项卡之间来回切换时,SelectedItem保持不变.但是当它的类型为TestViewModel
SelectedTest时,当tabitem失焦时,它被设置为null.
这是怎么回事?
小智 10
我有完全相同的问题,直到现在我无法弄清问题是什么.我在具有相同操作系统,.Net版本和硬件规格的4台不同机器上进行了测试,并且可以在其中两个机器中重现这个问题,而在其他机器中工作得很好.我能找到适合我的解决方法是在ItemsSource之前定义SelectedItem绑定.奇怪的是,如果我遵循这种模式,一切都按预期工作.也就是说,你只需要做以下事情:
<Window x:Class="ComboBoxInTabItemSpike.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel>
<TabControl>
<TabItem Header="1">
<ComboBox SelectedItem="{Binding MySelect}" ItemsSource="{Binding MyList}"/>
</TabItem>
<TabItem Header="2"/>
</TabControl>
<TextBlock Text="{Binding MySelect}"/>
</StackPanel>
</Window>
Run Code Online (Sandbox Code Playgroud)