c# WPF 循环遍历控件进行绑定数据
当wpf界面上有很多控件需要绑定值的时候,新新手一般是xxxx.Text =xxx.ToString();对于没有接触过MVVM的人来说,ViewModel还是有点学习成本的,
下面的方法是我以前项目上所使用的,这里记录下,也方便自己以后再次使用,废话不多说,直接上代码,肯定有很多不好的地方,因为我也是新手,请指教,谢谢
前端Demo.xmal
<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
{ One = "one_TextBlock", Two = false, Three = DateTime.Now, Four = 4 }; this.Fill<TestDTO>(dTO, this.st_child.Children);
要继承EcBaseWindow.cs
由于没有连接数据库,所有数据都是直接测试数据,Fill方法就可以将TestDTO中的数据绑定到界面上了
BaseDTO.cs如下:
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来处理控件并进行绑定数据