c# WPF 循环遍历控件进行绑定数据
当wpf界面上有很多控件需要绑定值的时候,新新手一般是xxxx.Text =xxx.ToString();对于没有接触过MVVM的人来说,ViewModel还是有点学习成本的,
下面的方法是我以前项目上所使用的,这里记录下,也方便自己以后再次使用,废话不多说,直接上代码,肯定有很多不好的地方,因为我也是新手,请指教,谢谢
前端Demo.xmal
1 2 3 4 5 6 | <StackPanel x:Name= "sp_Parent" > <TextBlock x:Name= "txb_One" ></TextBlock> <TextBox x:Name= "txt_Two" ></TextBox> <Label x:Name= "lbl_Three" ></Label> <TextBlock x:Name= "txb_Four" ></TextBlock> </StackPanel> |
请注意,StackPanel 为布局控件,当然其他的布局控件也是可以的,x:Name命名没有啥要求,但是,控件的 X:Name命名一定要注意,以控件缩写加下划线再加DTO里的字段,否则后面绑定不上。
后台Demo.xaml.cs
public class TestDTO: BaseDTO
{
public string One { get; set; }
public Boolean Two { get; set; }
public DateTime Three { get; set; }
public int Four { get; set; }
}
TestDTO dTO = new TestDTO
1 2 3 4 5 6 7 | <em id= "__mceDel" > { One = "one_TextBlock" , Two = false , Three = DateTime.Now, Four = 4 }; this .Fill<TestDTO>(dTO, this .st_child.Children);</em> |
要继承EcBaseWindow.cs
由于没有连接数据库,所有数据都是直接测试数据,Fill方法就可以将TestDTO中的数据绑定到界面上了
BaseDTO.cs如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public int Index { get ; set ; } public int PageSize { get ; set ; } public override string ToString() { JsonSerializerSettings settings = new JsonSerializerSettings(); JsonConvert.DefaultSettings = new Func<JsonSerializerSettings>(() => { //settings.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat; settings.DateFormatString = "yyyy-MM-dd HH:mm" ; settings.Formatting = Formatting.Indented; //空值处理 settings.NullValueHandling = NullValueHandling.Ignore; return settings; }); return JsonConvert.SerializeObject( this ); } |
要引入 using Newtonsoft.Json;
ECBaseWindow.cs
/// <summary> /// 表单填充 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="Element"></param> /// <param name="UIElement"></param> protected void Fill<T>(T Element, UIElementCollection UIElement) { JsonCollect.Instance.FillToElement(JsonConvert.SerializeObject(Element), UIElement); }
继承 Window
JsonCollect.cs
/// <summary> /// 将页面元素填充到DTO的json格式对象中,需要什么控件待补充 /// </summary> /// <param name="jobj"></param> /// <param name="element"></param> private void SetElementValue(JObject jobj, UIElement element) { if (element is TextBox) { TextBox textBox = element as TextBox; if (textBox.Name.ToLower().StartsWith("txt_")) { jobj[textBox.Name.Replace("txt_", string.Empty)] = textBox.Text.Trim(); } } if (element is TextBlock) { TextBlock textBlock = element as TextBlock; if (textBlock.Name.ToLower().StartsWith("txb_")) { jobj[textBlock.Name.Replace("txb_", string.Empty)] = textBlock.Text.Trim(); } } if (element is CheckBox) { CheckBox checkBox = element as CheckBox; if (checkBox.Name.ToLower().StartsWith("chk_")) { jobj[checkBox.Name.Replace("chk_", string.Empty)] = checkBox.IsChecked; } } if (element is PasswordBox) { PasswordBox passwordBox = element as PasswordBox; if (passwordBox.Name.ToLower().StartsWith("pwd_")) { jobj[passwordBox.Name.Replace("pwd_", string.Empty)] = passwordBox.Password; } } if (element is DatePicker) { DatePicker datePicker = element as DatePicker; if (datePicker.SelectedDate != null) { jobj[datePicker.Name.Replace("dpk_", string.Empty)] = datePicker.SelectedDate; } } if (element is Grid) { //递归拿到内容 jobj.Merge(ConvertToString((element as Grid).Children)); } if (element is StackPanel) { jobj.Merge(ConvertToString((element as StackPanel).Children)); } if (element is WrapPanel) { jobj.Merge(ConvertToString((element as WrapPanel).Children)); } if (element is DockPanel) { jobj.Merge(ConvertToString((element as DockPanel).Children)); } if (element is Border) { Border b = element as Border; SetElementValue(jobj, b.Child); } if (element is ComboBox) { ComboBox comboBox = element as ComboBox; if (comboBox.Name.ToLower().StartsWith("cbx_")) { if (jobj != null && jobj[comboBox.Name.Replace("cbx_", string.Empty)] != null) { comboBox.SelectedItem = jobj == null || jobj[comboBox.Name.Replace("cbx_", string.Empty)] == null ? "" : jobj[comboBox.Name.Replace("cbx_", string.Empty)]; } else { MessageBox.Show($"数据集中没有[{comboBox.Name.Replace("cbx_", string.Empty)}]字段,无法填充"); } } } } /// <summary> /// 将结果集的字符串形式填充到指定容器内的规范元素上 /// </summary> /// <param name="result">需要填充的结果集</param> /// <param name="uIElementCollection">传入的控件集</param> public void FillToElement(string result, UIElementCollection uIElementCollections) { JObject JResult = JsonConvert.DeserializeObject<JObject>(result); foreach (UIElement item in uIElementCollections) { ExplainElement(JResult, result, item); } } /// <summary> /// 将结果集的字符串形式填充到指定容器内的规范元素上 /// </summary> /// <param name="result">需要填充的结果集</param> /// <param name="uIElementCollection">传入的控件集</param> public void FillToElement(string result, UIElement uIElementCollection) { JObject JResult = JsonConvert.DeserializeObject<JObject>(result); ExplainElement(JResult, result, uIElementCollection); } /// <summary> /// 将JSON 元素解释道具体的控件上 /// </summary> /// <param name="JResult"></param> /// <param name="result"></param> /// <param name="uIElement"></param> private void ExplainElement(JObject JResult, string result, UIElement element) { if (element is TextBox) { TextBox textBox = element as TextBox; if (textBox.Name.ToLower().StartsWith("txt_")) { if (JResult != null && JResult[textBox.Name.Replace("txt_", string.Empty)] != null) { textBox.Text = JResult == null || JResult[textBox.Name.Replace("txt_", string.Empty)] == null ? "" : JResult[textBox.Name.Replace("txt_", string.Empty)].ToString(); } else { MessageBox.Show($"数据集中没有[{textBox.Name.Replace("txt_", string.Empty)}]字段,无法填充"); } } } if (element is TextBlock) { TextBlock textBlock = element as TextBlock; if (textBlock.Name.ToLower().StartsWith("txb_")) { if (JResult != null && JResult[textBlock.Name.Replace("txb_", string.Empty)] != null) { textBlock.Text = JResult == null || JResult[textBlock.Name.Replace("txb_", string.Empty)] == null ? "" : JResult[textBlock.Name.Replace("txb_", string.Empty)].ToString(); } else { MessageBox.Show($"数据集中没有[{textBlock.Name.Replace("txb_", string.Empty)}]字段,无法填充"); } } } if (element is Label) { Label label = element as Label; if (label.Name.ToLower().StartsWith("lbl_")) { if (JResult != null && JResult[label.Name.Replace("lbl_", string.Empty)] != null) { label.Content = JResult == null || JResult[label.Name.Replace("lbl_", string.Empty)] == null ? "" : JResult[label.Name.Replace("lbl_", string.Empty)].ToString(); } else { MessageBox.Show($"数据集中没有[{label.Name.Replace("lbl_", string.Empty)}]字段,无法填充"); } } } if (element is CheckBox) { CheckBox checkBox = element as CheckBox; if (checkBox.Name.ToLower().StartsWith("chk_")) { bool ischeck = false; if (JResult != null && JResult[checkBox.Name.Replace("chk_", string.Empty)] != null) { bool.TryParse(JResult[checkBox.Name.Replace("chk_", string.Empty)].ToString(), out ischeck); checkBox.IsChecked = ischeck; } else { MessageBox.Show($"数据集中没有[{checkBox.Name.Replace("chk_", string.Empty)}]字段,无法填充"); } } } if (element is Grid) { Grid grid = element as Grid; FillToElement(result, grid.Children); } if (element is StackPanel) { StackPanel stack = element as StackPanel; FillToElement(result, stack.Children); } if (element is WrapPanel) { WrapPanel wrap = element as WrapPanel; FillToElement(result, wrap.Children); } if (element is DockPanel) { DockPanel dock = element as DockPanel; FillToElement(result, dock.Children); } if (element is Border) { Border border = element as Border; ExplainElement(JResult, result, border.Child as UIElement); } if (element is ComboBox) { ComboBox comboBox = element as ComboBox; if (comboBox.Name.ToLower().StartsWith("cbx_")) { if (JResult != null && JResult[comboBox.Name.Replace("cbx_", string.Empty)] != null) { comboBox.SelectedItem = JResult == null || JResult[comboBox.Name.Replace("cbx_", string.Empty)] == null ? "" : JResult[comboBox.Name.Replace("cbx_", string.Empty)]; } else { MessageBox.Show($"数据集中没有[{comboBox.Name.Replace("cbx_", string.Empty)}]字段,无法填充"); } } } }
这里面才是重头戏,主要的作用就是将控件进行封装,依据控件的Name来处理控件并进行绑定数据
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 推荐几款开源且免费的 .NET MAUI 组件库
· 实操Deepseek接入个人知识库
· 易语言 —— 开山篇
· Trae初体验