Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dynamic controls experiment
#1
Although this doesn't really do anything useful, it may be helpful as an example of dynamically creating controls.
 
Code:
Copy      Help
// script "owned_d3.cs"
using System.Windows;
using System.Windows.Controls;

var rows = 0;
var b = new wpfBuilder("Select Sections").Width(185);
b.R.Add(out Button btn1, "Sections?").Add(out TextBox tb1).Width(80).Focus();
btn1.IsDefault = true;
btn1.ToolTip = "No. sections in field to right.";
tb1.ToolTip = "Enter number of sections." + Environment.NewLine + "Then press Enter or button.";

// Click handler: throw error if entry doesn't evaluate to int
btn1.Click += (o, e) => {
    int value;
    bool success = int.TryParse(tb1.Text, out value);
    if (success) {
        rows = tb1.Text.ToInt();
        // https://www.libreautomate.com/cookbook/Dialog%20-%20owned%2C%20non-modal%20(don%27t%20wait).html
        _Dialog2(b.Window);
    }
else {
        dialog.show("Error - not an integer!", title: "Error", secondsTimeout: 2);
        tb1.Text = "";
        return;
    }
};


b.End();
if (!b.ShowDialog()) return;

void _Dialog2(Window owner) {
    if (tb1.Text == "") {
        dialog.show("Please select # of sections", title: "Error", secondsTimeout: 2);
        return;
    }

    var b = new wpfBuilder("Dynamic controls").WinSize(300);
    for (int i = 0; i < rows; i++) {
        
        // Add buttons
        Button btnD = new Button();
        btnD.Name = "btn_" + i.ToString();
        btnD.Width = 80;
        btnD.Height = 30;
        btnD.Content = "Button " + (i + 1).ToString();
        
        // Add textboxes
        TextBox txtD = new TextBox();
        txtD.Name = "txt_" + i.ToString();
        txtD.Width = 200;
        
        // Add simple functionality
        btnD.Click += (o, e) => btnTestClick(o, txtD, btnD);
        
        // Add dynamically created controls to window
        b.R.Add(btnD).Add(txtD);
    }

    b.End();
    // see https://www.libreautomate.com/cookbook/Dialog%20-%20owned%2C%20non-modal%20(don%27t%20wait).html
    var w = b.Window;
    w.Owner = owner;
    w.Show();
    tb1.Text = "";
}


// Click handler with simple code
void btnTestClick(Object o, TextBox textbox, Button btn) {
    textbox.Text = "This text was added by " + btn.Content.ToString();
}

Best regards, burque505

   


Forum Jump:


Users browsing this thread: 1 Guest(s)