WPF 我无法在后面的代码中更新组合框值

WPF I cannot update a combobox value in code behind

我想更新以下组合框选择的项目:

<ComboBox ItemsSource="{Binding Path=DictUsers, UpdateSourceTrigger=PropertyChanged}" DisplayMemberPath="Key" SelectedValuePath="Value" SelectionChanged="ComboUser_SelectionChanged" SelectedValue="{Binding Edit.ProtLevel, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" />

ItemsSource,DictUsers,来自字典:

DictUsers = new Dictionary<string, int>();
DictUsers.Add(string.Empty, 0); 
foreach (cUser user in App.Users)
    DictUsers.Add(user.Name, user.ShowLevel);

我无法直接访问组合框,因为它在数据模板中,所以我想更新绑定值 (Edit.ProtLevel):

// Test
Edit.ProtLevel = 5;

但是组合框不会自行更新,这意味着所选项目不会更改。怎么了?

为了使您的绑定正常工作,绑定 属性 应该是 DependencyProperty 或在实现 INotifyPropertyChanged 的 class 内部,像这样应该可以工作:

public class Edit : INotifyPropertyChanged {
    private int _protLevel;

    public int ProtLevel {
        get => _protLevel;
        set {
            if (_protLevel != (_protLevel = value)) {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ProtLevel)));
            }
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
}

您可以阅读binding documentation here

还有一个简单的 INotifyPropertyChanged implementation here.