Combobox的SelectedValue在传递给null项时不反映更改

时间:2011-09-08 15:47:15

标签: c# silverlight mvvm

从一个项目到另一个项目时,我正在丢失所选值。我的combox框是这样的:

<local:ComboBoxEx x:Name="MYCB" 
       ItemsSource="{Binding Committente}" 
       SelectedValue="{Binding CommittenteSelected, Mode=TwoWay}"
       SelectionChanged="committente_SelectionChanged"
/>

Committente来自ViewModel:

private ObservableCollection<CommittenteV> _Committente;
public ObservableCollection<CommittenteV> Committente
{
    get { return _Committente; }
    set
    {
        _Committente = value;
        RaisePropertyChanged("Committente");
    }
}

在我的viewmodel的构造函数中,我得到了这样的集合:

Committente = ObservableCollectionConverter.GetObservableCollection<CommittenteV>(Service.getList);
Committente.Insert(0, null);

我添加一个空项目,以便能够拥有一个象征“所有项目”的项目

我的问题是从“真实”项目到这个空项目,我不会让CommittenteSelected等于null,而是选择先前项目的值。

如果这不起作用,我怎么能正确地实现这个“所有项目”功能来提供我的过滤器的组合框?

感谢您的帮助,

2 个答案:

答案 0 :(得分:1)

不是将此设置为null,而是可以向CommittenteV添加一个静态CommittenteV,它返回CommittenteV的“Unspecified / All”实例。类似于:

public static CommittenteV AllCommittente = new CommittenteV { Id = SomeUniqueValue };

然后检查此而不是null。当您将其添加到列表中时:

Committente.Insert(0, CommittenteV.AllCommittente);

也许给“AllCommittente”一个唯一的ID,永远不会被任何“真正的”委员会使用?它还允许您为此AllCommittente条目创建特定的显示标签(如果您有一个用于组合框中显示值的属性)。

答案 1 :(得分:0)

您还可以创建CommittenteV对象的子对象,这样当您检查选择了哪个对象时,您可以使用'is'运算符。

public class AllCommittenteV : CommittenteV, IRepresentAll {}

Committente.Insert(0, new AllCommittenteV());

if (SelectedItem is typeof(AllCommittenteV))
   // Use All
else
   // Use One

这为您打开了一扇门,让您可以创建一个可以注入托管VM的Processor类。将处理器类抛入SelectionChanged方法,您可以通过简单地更改注入的Precessor来更改类的整个行为。

使用该界面,您可以在任何时候表明此对象的合同,将该对象视为已选中。

相关问题