0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

binding完全に理解した(してない)

Posted at

多分すぐ忘れてしまうので備忘として。。。
そもそもbindingって何ですか?と言うレベルの馬鹿なのでバインドの目的も何しているのかも全然判らなかったんですが、要はview上のcontrolのプロパティに変数設定したいぜって時に使う事ですかね。いろいろ間違ってるかもしれないけど今は実用上そういう理解で。

今回は例として、TextBoxへの入力漏れを視覚的に判りやすくするために、未入力のTextboxの背景に色を付けたいって時、TextBoxのTextプロパティの値に応じてBackgroundプロパティを変化させたい、ってケースの場合の覚書です。

ViewのTextboxは以下の通り記述。

xaml
<TextBox x:Name="Textbox1" Background="{Binding ElementName=Textbox1, Path=Text, Converter={StaticResource IsTextEntered}}"/>

この時「Background」プロパティをバインドします。
「"{Binding ElementName=Sqid_Textbox, Path=Text, Converter={StaticResource IsTextEntered}}"」の「ElementName」は参照するエレメント名を指定します。
今回のケースでは自分自身のTextを参照するので自分自身のNameを指定していますが、例えば「テキストボックスに文字が入力されている場合にボタンを有効にする」みたいな時にはボタンのプロパティにテキストボックスのプロパティをバインドする事も出来ます。

「Path」は参照エレメントの実際に参照するプロパティを指定します。このケースではTextboxの「Text」を参照しています。

Bool値を単に連動させたい場合は不要と思いますが、今回は値を変換する必要がある為、converterを指定しています。

今回のケースではTextの値が空の場合は背景色をピンクに、Textに値が入力されている時は背景色を白に設定するので、以下のようにコンバーターを書きました。
今回はConvertBackが使わないのでthrow new NotImplementedException();と記述しています(実装が無いのでスローしています)。

cs
public class IsTextEnteredConverter : IValueConverter
{
	public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
	{
		return string.IsNullOrWhiteSpace((string)value) ? "pink" : "White";//?ここが値を変換している部分
	}

	public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
	{
		throw new NotImplementedException();
	}
}

今回使ったconverterのパラメータはvalueだけなので、他のパラメータは調べてないんですが、valueはbindingの記述のElementNameとPathで特定される対象の値になるようです。つまり今回はこのvalueはTextbox1.Textの値になります(ただしobjectとして取得しているのでstringに型変換が必要です)。
Textbox1.Textの値をstring.IsNullOrWhiteSpace()で真偽判定して、真(空である)場合はpink、偽(空ではない)場合にwhiteのstringを出力します。てゆうかbackgroundに指定する値stringで良かったんやねSystem.Windows.Media.Brush 型で指定しなきゃならんと思ってたのでちょっと引っかかりました。

※作成したconverterを引用できるようにするためにApplication.Resourcesに以下を追加してます

app.xaml
<Application.Resources>
    <ResourceDictionary>
        <local:IsSqidConverter x:Key="IsTextEntered"/>
    </ResourceDictionary>
</Application.Resources>

★体形的な学習など一切なしで付け焼刃だけでここまでやってきたので上記の短い記述にも間違いが多数含まれている可能性があります。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?