Winform binding like in WPF

I want to bind the Width property of the winform form to the text on the shortcut so that the shortcut text is updated with every mouse movement I made. Currently, I have only achieved an update when I clicked on an element in the form, but not a constant update (for example, if you change the text in the Resize handler). How to do it?

+3
source share
3 answers

You can bind the Width property by doing the following:

label1.DataBindings.Add(new Binding("Text", this, "Width"));

The problem is that the form does not notify the framework that the property has changed. The simplest of your best bets is likely to just do it with meat and potatoes:

protected override void OnResize(EventArgs e)
{
    base.OnResize(e);
    label1.Text = this.Width.ToString();
}

: , , ( , , ):

DataSource "System.Windows.Forms.Form".

:

public Form2()
{
   InitializeComponent();

   this.formBindingSource.DataSource = this;

   Binding binding = new Binding("Text", this.formBindingSource, "Size", true);

   binding.Format += new ConvertEventHandler(binding_Format);

   label1.DataBindings.Add(binding);
}

void binding_Format(object sender, ConvertEventArgs e)
{
    Size size = (Size)e.Value;
    e.Value = size.Width.ToString();
}

, , , .

+3

Resize - . , , , Resize Event. , //. .

private void OnFormResize(object sender, EventArgs args)
{
      Form frm = (Form) sender;
      txtWidth.Text = frm.Size.Width.ToString();
}
+1

, Width , Form WidthChanged.

Size

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        var binding = new Binding("Text", this, "Size", false, DataSourceUpdateMode.OnPropertyChanged);
        binding.Format += new ConvertEventHandler(binding_Format);

        label1.DataBindings.Add(binding);
    }

    void binding_Format(object sender, ConvertEventArgs e)
    {
        if (e.Value is Size)
        {
            e.Value = ((Size)e.Value).Width.ToString();
        }
    }
}
0

Source: https://habr.com/ru/post/1792856/


All Articles