いろいろ備忘録日記

主に .NET とか Go とか Flutter とか Python絡みのメモを公開しています。

DataBindingについて-01(書式を指定してバインディング)(Binding, DataSourceUpdateMode, formatString)

開発を行っていく上で、よくデータバインディングを利用すると思いますが
データバインディングをする際に、書式を指定することも出来ます。


その場合は、以下のようにBindingオブジェクトを作成します。

public Binding (
    string propertyName,
    Object dataSource,
    string dataMember,
    bool formattingEnabled,
    DataSourceUpdateMode dataSourceUpdateMode,
    Object nullValue,
    string formatString
)

ちょっと引数が多いですが、要は最後の引数にフォーマットを指定するって
事ですね。

以下、サンプルです。

// vim:set ts=4 sw=4 et ws is nowrap ft=cs:
using System;
using System.Drawing;
using System.Windows.Forms;

namespace Gsf.Demo
{

    public class BindingSample : Form
    {

        TextBox txtBinding1;
        TextBox txtBinding2;
        Button  btnDoBinding;

        public BindingSample()
        {
            InitializeComponent();
        }

        protected void InitializeComponent()
        {

            txtBinding1  = new TextBox();
            txtBinding2  = new TextBox();
            btnDoBinding = new Button();

            SuspendLayout();

            Text = "Binding Sample.";
            Size = new Size(500, 200);

            btnDoBinding.Text = "BINDING!!";

            txtBinding1.Width     = 150;
            txtBinding2.Width     = 150;

            txtBinding1.Location  = new Point(0, 10);
            txtBinding2.Location  = new Point((txtBinding1.Width + 10), 10);
            btnDoBinding.Location = new Point((txtBinding2.Location.X + txtBinding2.Width + 10), 10);

            btnDoBinding.Click += (s, e) => 
            {
                //
                // データをバインディング.
                //
                DateTime now = DateTime.Now;

                bool                 formattingEnabled = true;
                DataSourceUpdateMode updateMode        = DataSourceUpdateMode.OnValidation;
                object               nullValue         = null;
                string               format            = "d";

                Binding binding1 = new Binding("Text", now, "");
                Binding binding2 = new Binding("Text", now, "", formattingEnabled, updateMode, nullValue, format);

                txtBinding1.DataBindings.Add(binding1);
                txtBinding2.DataBindings.Add(binding2);

            };

            Load += (s, e) => 
            {
                ActiveControl = btnDoBinding;
            };

            Controls.AddRange(new Control[]{txtBinding1, txtBinding2, btnDoBinding});

            ResumeLayout();
        }

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new BindingSample());
        }
    }
}

上のサンプルでは、同じ値を2つのコントロールにそれぞれバインディングしています。
一つは普通にデータバインディング。もう一つは、書式を指定してバインディングしています。

画面を表示して、ボタンを押すと2つ目のテキストボックスには日付しか表示されません。