當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來處理控件並進行綁定數據
