C#ComboBox绑定显示错误的选定项

时间:2017-02-15 10:18:17

标签: c# wpf data-binding combobox

我创建的combobox和textblock绑定到viewmodel的相同属性

<ComboBox ItemsSource="{Binding LanguagesViewModel.Items}"
                  ItemTemplate="{StaticResource ComboBoxLanguageTemplate}"
                  SelectedItem="{Binding LanguagesViewModel.SelectedItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                  IsSynchronizedWithCurrentItem="True"
                  />
<TextBlock Text="{Binding LanguagesViewModel.SelectedItem.Language}" />

这导致我在组合框中显示错误的选择项(总是第一个)。 Textblock始终是正确的价值。当我在组合框中选择不同的值时,文本块会正确更新。如果我删除

  

IsSynchronizedWithCurrentItem = “真”

然后组合框显示“空”值。 SelectedItem of Language应该有正确的对象(通过debuging)。

LanguageViewModel包含languagemodel的obsertvablecollection。语言模型已实现覆盖equals和gethascode(通过resharper)并具有一个字符串属性语言:

protected bool Equals(LanguageModel other)
{
    return string.Equals(_language, other._language);
}

public override bool Equals(object obj)
{
    if (ReferenceEquals(null, obj)) return false;
    if (ReferenceEquals(this, obj)) return true;
    if (obj.GetType() != this.GetType()) return false;
    return Equals((LanguageModel) obj);
}

public override int GetHashCode()
{
    return (_language != null ? _language.GetHashCode() : 0);
}

组合框显示正确的项目有什么变化?

1 个答案:

答案 0 :(得分:0)

实际上,你的问题根本不清楚......

你说

  

这导致我在组合框中显示错误的选择项

但你怎么说呢?您尝试从VM设置当前项目吗?

请发布更多代码。

以下是组合框,文本块和视图模型之间交互的工作示例

XAML

<Window x:Class="So42246496.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:So42246496"
    mc:Ignorable="d"
    d:DataContext="{d:DesignInstance {x:Type local:LanguageViewModel}}"

    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <DataTemplate x:Key="ComboBoxLanguageTemplate">
        <TextBlock Text="{Binding Language}"></TextBlock>
    </DataTemplate>
</Window.Resources>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="47*"/>
        <RowDefinition Height="17*"/>
        <RowDefinition Height="17*"/>
    </Grid.RowDefinitions>

    <ComboBox ItemsSource="{Binding Items}"
              ItemTemplate="{StaticResource ComboBoxLanguageTemplate}"
              SelectedItem="{Binding SelectedItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
               Margin="2"
              />
    <TextBlock Text="{Binding SelectedItem.Language}" Grid.Row="1" Margin="2" />
    <Button Grid.Row="2" Content="Next item" Margin="2" Click="ButtonBase_OnClick"></Button>
</Grid>

MainWindow代码

public partial class MainWindow : Window
{
    private LanguageViewModel vm;

    public MainWindow()
    {
        vm = new LanguageViewModel();
        DataContext = vm;
        InitializeComponent();
    }

    private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
    {
        vm.NextItemFromViewModel();
    }
}

Viewmodel

public class LanguageViewModel : INotifyPropertyChanged
{
    private LanguageModel _selectedItem;
    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private int currentIndex = 1;
    public LanguageViewModel()
    {
        Items = new ObservableCollection<LanguageModel>();
        Items.Add(new LanguageModel { Language = "fr-FR" });
        Items.Add(new LanguageModel { Language = "en-GB" });
        Items.Add(new LanguageModel { Language = "en-US" });
        Items.Add(new LanguageModel { Language = "de-DE" });
        Items.Add(new LanguageModel { Language = "es-ES" });
        SelectedItem = Items[currentIndex];
    }

    public ObservableCollection<LanguageModel> Items { get; set; }

    public LanguageModel SelectedItem
    {
        get { return _selectedItem; }
        set { _selectedItem = value; OnPropertyChanged(); }
    }

    public void NextItemFromViewModel()
    {
        SelectedItem = Items[++currentIndex];
    }
}

语言模型

public class LanguageModel : INotifyPropertyChanged
{
    private string _language;

    public string Language
    {
        get { return _language; }
        set
        {
            _language = value;
            OnPropertyChanged();
        }
    }

    protected bool Equals(LanguageModel other)
    {
        return string.Equals(Language, other.Language);
    }

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != this.GetType()) return false;
        return Equals((LanguageModel)obj);
    }

    public override int GetHashCode()
    {
        return (Language != null ? Language.GetHashCode() : 0);
    }

    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}