Dynamically add textbox in WPF

前端 未结 2 494
南笙
南笙 2021-01-28 00:40

I am creating a textbox dynamically. I have 2 columns in my grid. I want to add new textbox to the row if the other textbox value=\"tea\". I want to create new textbox to corres

2条回答
  •  情书的邮戳
    2021-01-28 01:34

    Attached properties can be used to store such information so define an attached property in the class

        public static int GetGridRow(DependencyObject obj)
        {
            return (int)obj.GetValue(GridRowProperty);
        }
    
        public static void SetGridRow(DependencyObject obj, int value)
        {
            obj.SetValue(GridRowProperty, value);
        }
    
        // Using a DependencyProperty as the backing store for GridRow.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty GridRowProperty =
            DependencyProperty.RegisterAttached("GridRow", typeof(int), typeof(ViewModel), new PropertyMetadata(0));
    

    then use it to store the value of the row

    private void btn_addnew_Click(object sender, RoutedEventArgs e)
    {
        //1st Column TextBox
    
        txt1 = new TextBox();
        Grid.SetRow(txt1, i);
        SetGridRow(text1, i);
        ...
        grid1.Children.Add(txt1);
        count++;
    }
    

    then use it when u need it

    //How to set row here?
    
    Grid.SetRow(txt2, GetGridRow(txt1));
    Grid.SetColumn(txt2, 1);
    

提交回复
热议问题