Updating a ComboBox SelectedItem from code behind

2020-04-19 06:49发布

问题:

im having a View with a ComboBox bound to my viewModel property. Everything works fine but i actually want to reuse my View and need to update the controls with a given value. Setting the property wont update the visual UI even to event is fired and everyting looks good.

Everything works accept the ComboBox visual UI.

Tips?!

XAML control

<telerik:RadComboBox 
            ItemTemplate="{StaticResource SelectUserComboBoxTemplate}"
            SelectedItem="{Binding Path=SelectedUser, Mode=TwoWay,
            UpdateSourceTrigger=PropertyChanged}" 
            ItemsSource="{Binding Path=C_users}" 
            telerik:TextSearch.TextPath="displayName"
            Name="radComboBox1" 
            Margin="14,12,0,0" 
            Height="31" 
            VerticalAlignment="Top" 
            HorizontalAlignment="Left" 
            Width="253" 
            TextSearchMode="Contains"
            IsEditable="True"
            OpenDropDownOnFocus="True" 
            IsFilteringEnabled="True"
            >
    </telerik:RadComboBox>

The overloaded constructor that sets the values

    public TicketControlTabViewModel(ticket t)
    {
        activeTicket = t;
        SelectedUser = customerServiceClient.getUser(t.customer_users.id);
        MetaString = t.meta;
        Description = t.description;
        ActiveId = t.id.ToString();
        Selected_priority = t.priority;
        SelectedStatus = t.status;
        this.RefreshC_users();
        this.RefreshSupportDepartments();
        this.RefreshSupportUsers();
    }

The property in my ViewModel

    private customer_users selectedUser { get; set; }
    public customer_users SelectedUser
    {

        get {
            return this.selectedUser;
            }
        set {
              if (value != null){
              this.selectedUser = value;
              this.UpdateCustomerDepartment(value);
              this.OnPropertyChanged("SelectedUser");
              SaveTicket();
              }

            }
    }

回答1:

By default, WPF compares the SelectedItem by reference, not by value. That means if the SelectedItem isn't the exact same object in memory as the item in your ItemsSource, then the comparisom will return false and the item will not get selected.

For example, this will probably not work

MyCollection = new ObservableCollection<User>(DAL.GetUsers());
SelectedUser = DAL.GetUser(1);

however this would:

MyCollection = new ObservableCollection<User>(DAL.GetUsers());
SelectedUser = MyCollection.FirstOrDefault(p => p.Id == 1);

That's because the 2nd example sets the SelectedUser to an item that actually exists in MyCollection, while the 1st example might not. Even if the data is the same, they reference different objects in memory.

If your selected item doesn't reference the same item in memory as your ItemsSource item, then either use SelectedValue and SelectedValuePath to bind your ComboBox's default selection, or overwrite the .Equals() method of your class to return true if the data in the objects being compared is the same.

public override bool Equals(object obj)
{
    if (obj == null || !(obj == MyClass))
        return false; 

    return ((MyClass)obj).Id == this.Id);
}


回答2:

It may happen if you do not Items collection doesn't contain an item equal to SelectedItem. Check whether you have such an item (it may be that you just forgot to overload Equals in your class and it uses references comparison)



标签: c# wpf mvvm