开发者

Binding in winform like in WPF

I want to bind a winform's form's Width property to Text on a label so label's text gets updated every mouse movement I made. Currently I only achieved updating when some element on a form is clicked but not continious 开发者_如何学运维updating(like if you change text in Resize handler). How to do this thing?


You can bind to the Width property by doing this:

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

The problem there is the form isn't notifying the framework that the property has changed. Your easiest best bet is likely to just do it the meat and potatoes way:

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

EDIT: Okay, if you really want to use data binding, here is a way that works (but is like reaching around your head to scratch your ear):

Add an object data source to your form and set the DataSource to type "System.Windows.Forms.Form".

Next, add some code:

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

So like I said, it's complete overkill, but it works.


The Resize event is the correct event to handle. I'm not sure what continuous updating you are looking for, but if the form changes size, Resize Event fires. I believe this also includes size changes for minimize/maximize/restore. This should cover all changes to the size of the form.

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


You are right, binding to the Width property will not working correct because Form hasn't WidthChanged event.

You can bind to the Size property and use formating to format that

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜