WPF将ComboBoxItemSouce绑定到ObservableCollection,将SelectedItem绑定



我是WPF的新手,我很感兴趣这能不能完成。我在主窗口中为我的组合框控件定义了一个字符串数据源,如下所示:

public readonly ObservableCollection<string> _roles = new ObservableCollection<string>() { "User", "Admin", "Developer" };

我定义了一个模型:

public class LoginRequest : ValidationBase
{
private string _email;
private string _password;
private string _role;
[Required(ErrorMessage = "Email address is required")]
public string Email
{
get { return _email; }
set { SetValue(ref _email, value); }
}
[Required(ErrorMessage = "Password is required")]
[MinLength(8, ErrorMessage = "Password minimum length is 8 charachters.")]
public string Password
{
get { return _password; }
set { SetValue(ref _password, value); }
}
[Required(ErrorMessage = "Role is required")]
public string Role
{
get { return _role; }
set { SetValue(ref _role, value); }
}
}

这个模型在xaml中被定义为我的DataContext

<Window.DataContext><型号:LoginRequest/><Window.DataContext>

在表单中,我有一个ComboBox,用于绑定对象的Role属性。如果我从以下代码中设置combobox ItemSource属性,那就完美了:

cbRoles.ItemsSource = _roles;

但我很感兴趣,我能做这个吗?这是我的组合框的代码片段。

<StackPanel Grid.Row="2"
Margin="5"
Orientation="Vertical">
<Label x:Name="lblRole" 
Content="Role" />
<ComboBox ItemsSource="{Binding Path=Role,
UpdateSourceTrigger=PropertyChanged,
NotifyOnValidationError=True,
ValidatesOnDataErrors=True}"
DisplayMemberPath="{Binding SimpleStringProperty}"
SelectedValuePath="{Binding SimpleStringProperty}"
SelectedItem="{Binding SimpleStringProperty}"
IsSynchronizedWithCurrentItem="True" 
Text="Select Option"
Margin="1"
Height="20"
x:Name="cbRoles"/>
</StackPanel>

若要从XAML设置ComboBox.ItemsSource,必须使用数据绑定。若要使用数据绑定,源必须是public属性,这需要将_roles字段转换为public属性。

由于项是纯字符串,因此它没有任何属性,因此也没有路径。不能选择特性来提供显示值或选择值。必须移除CCD_ 5和CCD_ 6。

默认情况下,Binding.UpdateSourceTrigger设置为UpdateSourceTrigger.PropertyChanged

SimpleStringPropertyLoginRequest上不存在。CCD_ 11应该绑定到CCD_ 12。

主窗口.xaml.cs

partial class MainWindow : Window
{
public ObservableCollection<string> Roles { get; }
public MainWindow()
{
InitializeComponent();
this.Roles = new ObservableCollection<string>() { "User", "Admin", "Developer" };
}
}

主窗口.xaml

<ComboBox ItemsSource="{Binding Path=Roles, 
RelativeSource={RelativeSource AncestorType=Window}},
NotifyOnValidationError=True,
ValidatesOnDataErrors=True}"
SelectedItem="{Binding Role}"
IsSynchronizedWithCurrentItem="True" />

最新更新