从后面的代码更新 ComboBox SelectedItem

Per*_*son 2 c# wpf mvvm

我有一个带有绑定到我的 viewModel 属性的 ComboBox 的视图。一切正常,但我实际上想重用我的视图,并且需要使用给定值更新控件。即使事件被触发并且一切看起来都很好,设置属性也不会更新视觉 UI。

一切正常接受 ComboBox 视觉 UI。

尖端?!

XAML 控制

<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>
Run Code Online (Sandbox Code Playgroud)

设置值的重载构造函数

    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();
    }
Run Code Online (Sandbox Code Playgroud)

我的 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();
              }

            }
    }
Run Code Online (Sandbox Code Playgroud)

Rac*_*hel 5

默认情况下,WPFSelectedItem通过引用进行比较,而不是通过值进行比较。这意味着如果SelectedItem内存中的对象与 中的项目不完全相同ItemsSource,则比较将返回 false 并且该项目将不会被选择。

例如,这可能不起作用

MyCollection = new ObservableCollection<User>(DAL.GetUsers());
SelectedUser = DAL.GetUser(1);
Run Code Online (Sandbox Code Playgroud)

然而这会:

MyCollection = new ObservableCollection<User>(DAL.GetUsers());
SelectedUser = MyCollection.FirstOrDefault(p => p.Id == 1);
Run Code Online (Sandbox Code Playgroud)

这是因为第二个示例将 SelectedUser 设置为 中实际存在的项目MyCollection,而第一个示例可能不存在。即使数据相同,它们引用内存中的不同对象。

如果您选择的项目在内存中未引用与 ItemsSource 项目相同的项目,则可以使用SelectedValueSelectedValuePath绑定 ComboBox 的默认选择,或者覆盖.Equals()类的方法,以便在比较对象中的数据相同时返回 true 。

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

    return ((MyClass)obj).Id == this.Id);
}
Run Code Online (Sandbox Code Playgroud)