我有一个像这样定义的ComboBox:
<ComboBox
ItemsSource="{Binding Choices}"
SelectedItem="{Binding Value}"
Text="{Binding Text}"
IsEditable="True"
TextSearch.TextPath="Label"
DisplayMemberPath="Label" />
以下是我的观点型号:
public class ComboBoxViewModel : ViewModelBase
{
private string _selectedCode;
public ReadOnlyObservableCollection<ComboBoxItem> Choices { get; }
public ComboBoxItem Value
{
get { return this.Choices.FirstOrDefault(choice => choice.Code == _selectedCode); }
set
{
this.SetCode(value?.Code)
}
}
public string Text
{
get { return this.Value?.Label ?? _selectedCode; }
set
{
// Only set the code if no pre-defined code can be selected
if (this.Value == null)
{
this.SetCode(value)
}
}
}
public ComboBoxViewModel()
{
this.Choices = [..];
}
public bool SetCode(string code)
{
if (_selectedCode != code)
{
_selectedCode = code;
// Tried all the combination with/without/different order with no change
this.RaisePropertyChanged(nameof(this.Value));
this.RaisePropertyChanged(nameof(this.Text));
}
}
}
public class ComboBoxItem
{
public string Code { get; }
public string Label { get; }
public ComboBoxItem(string code, string label)
{
this.Code = code;
this.Label = label;
}
}
Choices
集合初始化为一对:Code,Label
。我想向用户显示Label
并在我的业务层中使用Code
。我还希望我的用户在ComboBox中输入自己的代码(这就是为什么IsEditable
依赖属性设置为True
以及为什么我还在我的ViewModel上绑定Text
。
在Control上直接绑定我的ViewModel时,Everythings工作正常。如果需要,_selectedCode
将使用选定的Choices
元素或手动输入进行更新。
当我使用SetCode方法预先设置_selectedCode
时,会出现问题。当我在ComboBox中选择新的现有Choice
时,不再更新Value属性...
是否可以绑定ComboBox的SelectedItem
和Text
?您是否知道为什么在编程初始化后未更新绑定属性?这就像事件不再被解雇了......