【发布时间】:2011-03-20 23:46:26
【问题描述】:
我有一个组合框,其 SelectedItem 和 ItemSource 属性绑定到视图模型。 ItemSource 中的对象是时间敏感的,因为对象过期,我只能将集合中的活动项目设置为 ItemSource。现在在某个时刻,selectedItem 对象可能不在 ItemSource 中。 我认为 ItemSource 的正常行为是只允许从 ItemSource 集合中选择对象,但在这种情况下,我确实想选择一个不再在 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”,但在打开下拉菜单时不应该有任何项目。
【问题讨论】:
标签: wpf combobox selecteditem