c # WPF data binding loop through the controls

When there are a lot of controls on wpf interface needs to bind values, the new novice generally xxxx.Text = xxx.ToString (); for people who have no contact with the MVVM, ViewModel still a little learning costs,

I used the following method is used on the project, under the record here, but also to facilitate their reuse in the future, ado, directly on the code, there must be a lot of bad places, because I am also a novice, please advise, thank you

The front 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>

 Please note, StackPanel to layout controls, of course, the other layout controls are also possible, x: Name name is not what the requirements, however, control X: Name name must pay attention to, in order to control the abbreviation underlined plus DTO in the field, or else not binding on the back.

Background 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);

To inherit EcBaseWindow.cs

Since the database is not connected, test data all data are direct, the Fill method can be used to bind the data to the interface TestDTO in the 

BaseDTO.cs as follows:

  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);
        }

 To be introduced  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);
        }

Extends Window

JsonCollect.cs

 ///  <the Summary> 
        /// will fill the page elements to json format object DTO's, what controls need to be supplemented
         ///  </ the Summary> 
        ///  <param name = "jobj"> </ param> 
        // /  <param name = "Element"> </ param> 
        Private  void SetElementValue (a JObject jobj, the UIElement Element) 
        { 
            IF (Element IS the TextBox) 
            { 
                the TextBox the textBox = Element AS the 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)]; 
                    } 
                    the else 
                    { 
                        MessageBox.Show ($ " dataset without [{comboBox.Name.Replace ( " cbx_ " , string.Empty)}] field is not filled " ); 
                    } 
                } 
            } 
        } 

        / //  <Summary> 
        /// filled string to the specification of the result set in the specified container element
         ///  </ Summary> 
        ///  <param name = "result"> needs to be filled result set </ param > 
        ///  <param name = "uIElementCollection"> incoming control set </param>
        public void FillToElement ( String Result, UIElementCollection uIElementCollections) 
        { 
            a JObject JResult = JsonConvert.DeserializeObject <a JObject> (Result);
             the foreach (the UIElement Item in uIElementCollections) 
            { 
                ExplainElement (JResult, Result, Item); 
            } 
        } 

        ///  <Summary> 
        // / filled string to the specification of the result set in the specified container element
         ///  </ Summary> 
        ///  <param name = "result"> needs to be filled result set </ param> 
        ///  <param name = "uIElementCollection">Incoming set of controls </ 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)] the ToString ();. 
                    } 
                    the else 
                    { 
                        MessageBox.Show ($ " dataset no [ textBox.Name.Replace {( " txt_ " , string.Empty)}] field is not filled " ); 
                    } 
                } 
            } 
            IF (Element IS the 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)] the ToString ();. 
                    } 
                    the else 
                    { 
                        MessageBox.Show ($ " dataset without [{textBlock.Name.Replace ( " , TXB_ " , string.Empty)}] field is not filled " ); 
                    } 
                } 
            } 
            IF (Element IS the label) 
            { 
                the 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)] the ToString (); 
                    } 
                    the else 
                    { 
                        MessageBox.Show ($ " dataset without [{label.Name.Replace ( " lbl_ " , string.Empty) }] field is not filled " ); 
                    } 
                } 
            } 
            IF (Element IS the checkBox) 
            { 
                the checkBox checkBox = Element AS the 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;
                    }
                    the else 
                    { 
                        MessageBox.Show ($ " dataset without [{checkBox.Name.Replace ( " chk_ " , string.Empty)}] field is not filled " ); 
                    } 
                } 
            } 
            IF (Element IS the Grid) 
            { 
                the Grid Grid = Element AS the Grid; 
                FillToElement (Result, grid.Children); 
            } 
            IF (Element IS the StackPanel) 
            { 
                the 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)]; 
                    } 
                    the else 
                    { 
                        MessageBox.Show ($ " dataset without [{comboBox.Name.Replace ( " cbx_ " , string.Empty)}] field can not be filled .");
                    }
                }
            }
        }

There is the main event, the main role is to encapsulate the controls, according to the Name control to process control and data binding

 

Guess you like

Origin www.cnblogs.com/zhixiaoxiao/p/11897143.html