
本示例的注意点:
CurrentAccount 不要绑定到 Combobox 的 SelectedItem 上,会被置空,置空后无法回传用户输入的数据
在关键操作处对 CurrentAccount 进行克隆,使其区别于列表内的引用对象
ui
| <StackPanel Margin="5"> |
| <ComboBox |
| Margin="4" |
| DisplayMemberPath="UserName" |
| IsEditable="True" |
| ItemsSource="{Binding Accounts}" |
| SelectionChanged="{t:Action SelectAccount(@s.SelectedItem)}" |
| Text="{Binding CurrentAccount.UserName, |
| UpdateSourceTrigger=LostFocus}" /> |
| <TextBox Margin="4" Text="{Binding CurrentAccount.Password}" /> |
| <Button |
| Margin="4" |
| Click="{t:Action Login()}" |
| Content="登录" /> |
| </StackPanel> |
model
| |
| |
| |
| public class Account |
| { |
| public string UserName { get; set; } |
| public string Password { get; set; } |
| |
| public Account() |
| { |
| |
| } |
| |
| public Account(string userName, string password) |
| { |
| UserName = userName; |
| Password = password; |
| } |
| public override string ToString() |
| { |
| return $"{UserName},{Password}"; |
| } |
| } |
| |
| public class MainWindowViewModel : ViewModelBase |
| { |
| public ObservableCollection<Account> Accounts |
| { |
| get => GetProperty<ObservableCollection<Account>>(); |
| set => SetProperty(value); |
| } |
| |
| |
| |
| |
| |
| public Account CurrentAccount { get => GetProperty<Account>(); set => SetProperty(value); } |
| |
| |
| private Account Clone(Account account) |
| { |
| return new Account(account.UserName, account.Password); |
| } |
| |
| public MainWindowViewModel() |
| { |
| |
| Accounts = new ObservableCollection<Account>() |
| { |
| new Account("user1","pwd1"), |
| new Account("user2","pwd2"), |
| }; |
| CurrentAccount = Clone(Accounts[0]); |
| } |
| |
| |
| |
| |
| |
| |
| public void SelectAccount(Account account) |
| { |
| |
| if (account != null) |
| { |
| |
| CurrentAccount = Clone(account); |
| } |
| } |
| |
| public void Login() |
| { |
| if (CurrentAccount == null) |
| { |
| CurrentAccount = new Account(); |
| } |
| if (string.IsNullOrEmpty(CurrentAccount.UserName) || string.IsNullOrEmpty(CurrentAccount.Password)) |
| { |
| MessageBox.Show($"账号或密码为空"); |
| return; |
| } |
| |
| |
| |
| var hasCurrent = Accounts.Where(x => x.UserName == CurrentAccount.UserName).Count() > 0; |
| |
| if (!hasCurrent) { Accounts.Add(Clone(CurrentAccount)); } |
| |
| |
| |
| MessageBox.Show($"当前账号:{CurrentAccount}"); |
| |
| } |
| } |
| |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步