単純に Binding することができないシチュエーションがあります。例えば、片方が値で、片方がテキスト、である場合などで表示の方法を変換したい場合などがあります。ここでは int と string の変換をデータバインディングに絡める方法を記載します。
| コンパイラ : | Visual Studio 2013 | |
| 言語 : | C#, Form | |
スライダーの値をテキストボックスへ表示するデータバインディングを行うプログラムの作成を行います。
まずは Form
を使ったプロジェクトを新規作成し、以下のような画面を作成。
| 部品 | 説明 |
| Form | タイトルを”Bindingテスト”とする。 |
| TextBox | TrackBarの値をテキスト表示。 |
| TrackBar | 0~100 を設定可能。初期値 0。 |
| Button | "Close"を表示。ボタンクリックでプログラム終了。 |
まずは部品を貼り付けます。

各部品のプロパティを設定します。

TextBox と TrackBar をデータバインディングします。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace test_Binding_Format_Parse
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Close();
}
private void Form1_Load(object sender, EventArgs e)
{
Binding b = new Binding("Text", trackBar1, "Value" );
textBox1.DataBindings.Add(b);
}
}
}
実行すると次のような画面になります。

次に、スライダーの値範囲を 0~100 のままに、テキストボックスの表示を 0.00~1.00 にすることを行います。
つまりスライダーの値を
1/100 してテキストボックスに表示する、または テキストボックスの値を ×100 してスライダーへ設定する、の2つの処理が必要です。
これを行うために、以下のように Format、Parse のイベントを加えます。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace test_Binding_Format_Parse
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Close();
}
private void Form1_Load(object sender, EventArgs e)
{
Binding b = new Binding("Text", trackBar1, "Value" );
b.Format += new ConvertEventHandler( IntToString );
b.Parse += new ConvertEventHandler( StringToInt );
textBox1.DataBindings.Add(b);
}
private void IntToString(object sender, ConvertEventArgs cevent)
{
// The method converts only to string type. Test this using the DesiredType.
if (cevent.DesiredType != typeof(string))
{
return;
}
decimal data = ((int)cevent.Value);
data /= 100;
cevent.Value = data.ToString("F2");
}
private void StringToInt(object sender, ConvertEventArgs cevent)
{
// The method converts only to string type. Test this using the DesiredType.
if (cevent.DesiredType != typeof(int))
{
return;
}
cevent.Value = (int)(decimal.Parse((string)cevent.Value)*100);
}
}
}

意図通りうまく動きました。
本ページの情報は、特記無い限り下記 MIT ライセンスで提供されます。
| 2023-08-31 | - | ページデザイン更新 |
| 2014-03-15 | - | 新規作成 |