我有一个带有以下选项的组合框:“ HardDelete”,“ SoftDelete”,“ MoveToDeletedItems”
我希望默认选择与EmailAction对象的以下属性匹配:
public DeleteMode DeleteMode { get; set; }
这是我用来尝试设置的代码行:
cmboDelMode.SelectedItem = emailActionInstance.DeleteMode.ToString();
相关的XAML:
<ComboBox x:Name="cmboDelMode" HorizontalAlignment="Left" Margin="149,218,0,0" VerticalAlignment="Top" Width="120">
<ComboBoxItem Content="HardDelete" HorizontalAlignment="Left" Width="118"/>
<ComboBoxItem Content="SoftDelete" HorizontalAlignment="Left" Width="118"/>
<ComboBoxItem Content="MoveToDeletedItems" HorizontalAlignment="Left" Width="118"/>
</ComboBox>
当前,组合框默认为空,因此无法正常工作。我可以使用“ emailActionInstance.DeleteMode.ToString();”查看文本框中的数据,所以看来我可能只是错误地设置了所选项目?
问题是,除非ComboBox包含您要为其设置的项目,否则设置ComboBox.SelectedItem不会起作用。在您的情况下,您的ComboBox充满了三个ComboBoxItem对象,这些对象的Content属性设置为字符串。所以ComboBox.SelectedItem是一个ComboBoxItem。您试图将ComboBox.SelectedItem设置为字符串,这将不等于ComboBox中包含的任何对象。因此,什么也没有发生。
我建议像下面这样为您的ComboBox设置Binding:
<ComboBox ItemsSource="{Binding DeleteModes}" SelectedItem="{Binding SelectedDeleteMode}" />
然后创建要绑定的ViewModel。如果将枚举绑定到ComboBox,它将正确显示,因此您无需调用DeleteMode.ToString():
public class ViewModel : INotifyPropertyChanged
{
public ViewModel()
{
DeleteModes = new ObservableCollection<DeleteMode>
{ DeleteMode.HardDelete, DeleteMode.SoftDelete,
DeleteMode.MoveToDeletedItems };
}
public event PropertyChangedEventHandler PropertyChanged;
DeleteMode _selected_delete_mode;
public DeleteMode SelectedDeleteMode {
get { return _selected_delete_mode; }
set {
_selected_delete_mode = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SelectedDeleteMode"));
}
}
ObservableCollection<DeleteMode> _delete_modes;
public ObservableCollection<DeleteMode> DeleteModes {
get { return _delete_modes; }
set {
_delete_modes = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("DeleteModes"));
}
}
public void update_mode(DeleteMode mode) => SelectedDeleteMode = mode;
}