我有一个组合框,其SelectedItem和ItemSource属性绑定到viewmodel。 ItemSource中的对象对时间敏感,因为对象到期,我只能将集合中的活动项目设置为ItemSource。现在在某个点上,selectedItem对象可能不在ItemSource中。 我认为ItemSource的正常行为是只允许从ItemSource集合中选择对象,但在这种情况下,我确实想选择一个不再位于ItemSource中的对象。 我该如何实现这种行为?我会在这里发布一些代码来支持我的问题。将ComboBox SelectedItem设置为不存在于ItemSource中的数据对象
Window.xaml
<Window x:Class="ExpiredSelectedItem.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ComboBox Height="23"
HorizontalAlignment="Left"
Margin="184,68,0,0"
Name="comboBox1"
VerticalAlignment="Top"
Width="120"
ItemsSource="{Binding CustomList}"
SelectedItem="{Binding ActiveItem}"
SelectedValue="Code"
SelectedValuePath="{Binding ActiveItem.Code}"
DisplayMemberPath="Code"
/>
</Grid>
Window.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace ExpiredSelectedItem
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
CustomList = new List<DomainObject>();
CustomList.AddRange(new DomainObject[] {
new DomainObject() { Code = "A", IsActive =true},
new DomainObject() { Code ="B", IsActive = true},
new DomainObject() { Code = "C", IsActive =true},
});
ActiveItem = new DomainObject() { Code = "D", IsActive = false };
this.DataContext = this;
}
public List<DomainObject> CustomList { get; set; }
public DomainObject ActiveItem { get; set; }
}
public class DomainObject
{
public string Code { get; set; }
public bool IsActive { get; set; }
}
}
即使我在选择代码隐藏,当代码d组合框加载第一个项目(A)被选中。预期的行为是应该在文本框中选择“D”,但打开下拉菜单时不应该有任何项目。
感谢您指出了这一点乔恩 - 对了selectedValue和selectedvaluePath是用于不同的目的,并在短短的噪音这个例子。但是,这并不能解决问题。现在,而不是选择第一个项目,选定的文本显示一个空白。正如在上面的帖子中提到的,我想要选择“D”。 – Arjun 2011-03-21 04:12:12