绑定TwoWay到SelectedItem:初始化时“错误的方式”同步

时间:2013-01-24 16:38:15

标签: wpf binding collectionviewsource

我正在尝试将DataContext的属性绑定到ComboBox上的SelectedItem,如下所示:

<ComboBox x:Name="ElementSelector" 
          ItemsSource="{Binding Source={StaticResource Elements}}"
          DisplayMemberPath="ElementName"
          SelectedItem="{Binding ValueElement, Mode=TwoWay}">

其中 Elements 资源是CollectionViewSource(不知道,这是否重要)。

初始化所有内容后,ValueElement的属性DataContext将设置为CollectionViewSource中的第一项。我想要的是反过来初始化它:我想将ComboBox的SelectedItem设置为属性的值,如果不包含匹配项,则为null。

如何做到这一点?

编辑 - 补充信息:

ComboBox是DataTemplate的一部分:

<DataTemplate x:Key="ReferenceTemplate" 
              DataType="viewModels:ElementMetaReferenceViewModel">
   <StackPanel Orientation="Horizontal">
      <StackPanel.Resources>
         <ResourceDictionary>
            <views:ElementsForReferenceViewSource x:Key="Elements" 
                                                  Source="{Binding  DataContext.CurrentProject.Elements, ElementName=Root}" 
                                                  ReferenceToFilterFor="{Binding}"/>
         </ResourceDictionary>
      </StackPanel.Resources>

      <TextBlock Text="{Binding PropertyName}"/>
      <ComboBox x:Name="ElementSelector" 
                ItemsSource="{Binding Source={StaticResource Elements}}"
                DisplayMemberPath="ElementName" 
                SelectedItem=""{Binding ValueElement, Mode=TwoWay}" />

   </StackPanel>
</DataTemplate>

ElementsForReferenceViewSource只是从CollectionViewSource派生而来,并实现了一个额外的DependencyProperty,用于过滤。

DataContext中的CollectionViewSource个项目如下所示:

public class ElementMetaReferenceViewModel : ViewModelBase<ElementMetaReference, ElementMetaReferenceContext>
{
   ...
    private ElementMetaViewModel _valueElement;

    public ElementMetaViewModel ValueElement
    {
        get { return _valueElement; }
        set
        {
            if (value == null) return;
            _valueElement = value;
            Model.TargetElement = value.Model;
        }
    }

    ...
}

1 个答案:

答案 0 :(得分:0)

遇到同样问题的人

上面的代码按预期工作。解决方案是让幕后的东西正确。确保ViewModel的实例(您要绑定的属性的值)确实包含在CollectionViewSource中。

在我的情况下,问题是错误地反序列化对象树,因此对象被实例化两次。然后,对于每个对象,初始化了一个不同的ViewModel,然后显然该属性的值未包含在列表中。

<强>备注

要检查这是否是您的问题,您可以尝试以下操作:

覆盖ComboBox中显示的ViewModel的ToString()方法,如下所示:

public override string ToString()
{
   return "VM"+ Model.GetHashCode().ToString();
}

然后,您可以轻松地将源集合中的项目与属性上的值进行比较。不是最专业的方式,但它为我做了工作。