我有一个包含一些字段和两个组合框的表单。我的视图模型包含User
类的一些实例,该类包含name
和profile
属性。
ViewModel
public class UserViewModel: INotifyPropertyChanged
{
private ObservableCollection<User> usersList = new ObservableCollection<User>();
private User selectedUser = new User();
private User newUser = new User();
public UserViewModel()
{
}
public ObservableCollection<User> UsersList
{
get
{
return this.usersList;
}
set
{
this.usersList = value;
this.OnPropertyChanged();
}
}
public User SelectedUser
{
get
{
return this.selectedUser;
}
set
{
this.selectedUser = value;
this.OnPropertyChanged();
}
}
public User NewUser
{
get
{
return this.newUser;
}
set
{
this.newUser = value;
this.OnPropertyChanged();
}
}
private void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
隐藏代码
this.userViewModel = new UserViewModel();
this.DataContext = this.userViewModel;
XAML
<-- The DataContext for this ComboBox is the entire UserViewModel -->
<ComboBox
Height="Auto"
Width="Auto"
IsEditable="True"
IsTextSearchCaseSensitive="False"
SelectedItem="SelectedUser">
<ComboBoxItem Content="Mary" IsSelected="True"></ComboBoxItem>
<ComboBoxItem Content="John"></ComboBoxItem>
</ComboBox>
如果我从第一个组合框中选择一个用户,则所有表单字段都将填充现有数据。无论我选择哪个用户,都将通过SelectedItem属性将其保存在SelectedUser
中。
<Grid>
<Grid.DataContext>
<PriorityBinding>
<Binding Path="SelectedUser" Converter="{StaticResource NullToDependencyPropertyUnsetConverter}" />
<Binding Path="NewUser" />
</PriorityBinding>
</Grid.DataContext>
[...]
<-- The DataContext for this ComboBox will be SelectedUser or NewUser, depending on the case -->
<ComboBox
Name="profileComboBox"
Height="Auto"
Width="Auto"
IsEditable="True"
IsTextSearchCaseSensitive="False"
SelectedItem="Profile">
<ComboBoxItem Content="User" IsSelected="True"></ComboBoxItem>
<ComboBoxItem Content="Admin"></ComboBoxItem>
</ComboBox>
[...]
</Grid>
根据SelectedUser
是否为空,ComboBox将NewUser
或SelectedUser
作为DataContext。然后,无论我选择什么配置文件,它都将通过SelectedItem属性保存在先前选择的用户的Profile
属性中。
我的问题是第二个组合框应自动选择刚在第一个组合框中选择的用户的相应配置文件(“用户”或“管理员”)。仅使用XAML可以实现吗?
答案 0 :(得分:0)
将第二个SelectedItem
的{{1}}绑定到当前所选ComboBox
的{{1}}属性中:
Profile
或
User
还要从SelectedItem="{Binding SelectedUser.Profile}"
中删除项目,并将SelectedItem="{Binding SelectedItem.Profile, ElementName=userComboBox}"
属性设置为ComboBox
类型的属性的名称:
DisplayMemberPath