WPF写一个用户选择控件,从下拉框中选择用户,每一个用户都显示出来
时间: 2024-03-20 07:44:07 浏览: 76
用WPF实现多选下拉框
4星 · 用户满意度95%
下面是一个简单的WPF用户选择控件的示例代码,其中使用了ComboBox和ListBox控件:
XAML代码:
```xml
<UserControl x:Class="UserSelectorControl.UserSelector"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<ComboBox x:Name="UserComboBox" SelectionChanged="UserComboBox_SelectionChanged">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding UserName}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<ListBox x:Name="SelectedUsersListBox" Grid.Row="1">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding UserName}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</UserControl>
```
C#代码:
```csharp
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
namespace UserSelectorControl
{
public partial class UserSelector : UserControl
{
public static readonly DependencyProperty UsersProperty =
DependencyProperty.Register("Users", typeof(ObservableCollection<User>), typeof(UserSelector), new PropertyMetadata(null));
public ObservableCollection<User> Users
{
get { return (ObservableCollection<User>)GetValue(UsersProperty); }
set { SetValue(UsersProperty, value); }
}
public static readonly DependencyProperty SelectedUsersProperty =
DependencyProperty.Register("SelectedUsers", typeof(ObservableCollection<User>), typeof(UserSelector), new PropertyMetadata(null));
public ObservableCollection<User> SelectedUsers
{
get { return (ObservableCollection<User>)GetValue(SelectedUsersProperty); }
set { SetValue(SelectedUsersProperty, value); }
}
public UserSelector()
{
InitializeComponent();
Users = new ObservableCollection<User>();
SelectedUsers = new ObservableCollection<User>();
}
private void UserComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (UserComboBox.SelectedItem != null)
{
var user = (User)UserComboBox.SelectedItem;
if (!SelectedUsers.Contains(user))
{
SelectedUsers.Add(user);
}
}
}
}
public class User
{
public string UserName { get; set; }
}
}
```
在使用该控件时,需要为Users属性设置一个包含所有用户的ObservableCollection,例如:
```xml
<Window x:Class="UserSelectorControl.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:userSelector="clr-namespace:UserSelectorControl"
Title="MainWindow" Height="450" Width="800">
<Grid>
<userSelector:UserSelector Users="{Binding AllUsers}" SelectedUsers="{Binding SelectedUsers}" />
</Grid>
</Window>
```
其中,AllUsers和SelectedUsers都是在ViewModel中定义的ObservableCollection。
阅读全文