WPF中如何跳过已有Content的首个Button,将输入内容赋值给下一个Button
问题修复方案
原代码核心问题
- 进入方法就直接修改
btn_contact1的内容,没有先判断它是否已存在内容,导致第一个按钮永远会被覆盖 - 还没完成所有按钮的赋值逻辑,就提前清空了输入框内容,后续给其他按钮赋值时只能拿到空字符串
- 判断条件逻辑错误:
btn_contact1 == Content是把按钮对象和当前窗口的Content属性对比,完全不符合「判断按钮是否已有内容」的需求
修复后的代码
private void btn_add_Click(object sender, RoutedEventArgs e) { // 先拼接要显示的内容,避免后续输入框清空拿不到值 string fullName = $"{firstname.Text} {lastname.Text}".Trim(); // 内容为空时直接跳出,避免给按钮赋值空白内容 if (string.IsNullOrEmpty(fullName)) return; // 按顺序判断按钮是否为空,找到第一个空按钮再赋值 if (string.IsNullOrEmpty(btn_contact1.Content?.ToString())) { btn_contact1.Content = fullName; } else if (string.IsNullOrEmpty(btn_contact2.Content?.ToString())) { btn_contact2.Content = fullName; } else if (string.IsNullOrEmpty(btn_contact3.Content?.ToString())) { btn_contact3.Content = fullName; } // 全部逻辑执行完成再清空输入框 firstname.Text = ""; lastname.Text = ""; phonenumber.Text = ""; }
可选优化方案
如果后续需要扩展更多联系人按钮,可以把按钮放到数组中遍历,不用重复写判断逻辑:
private void btn_add_Click(object sender, RoutedEventArgs e) { string fullName = $"{firstname.Text} {lastname.Text}".Trim(); if (string.IsNullOrEmpty(fullName)) return; // 把所有联系人按钮存入数组,后续新增按钮只需要补充到数组里即可 Button[] contactBtns = { btn_contact1, btn_contact2, btn_contact3 }; foreach (var btn in contactBtns) { if (string.IsNullOrEmpty(btn.Content?.ToString())) { btn.Content = fullName; break; } } firstname.Text = ""; lastname.Text = ""; phonenumber.Text = ""; }
内容的提问来源于stack exchange,提问作者ImStillLearning
相关产品推荐
相关产品推荐

