2
2

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 5 years have passed since last update.

Xaml (WPF) の中に C# script を記述する その2

Last updated at Posted at 2016-10-09

前の記事 に少し手を加えました。

作成したソースは GitHub で公開しています。

今回は、TriggerAction に加えて IValueConverter, ICommand も実装してみました。
Converter と Command はマークアップ拡張にできるので、ワンライナーで書くのがいいと思います。

使用例

ScriptCommand

バインドした ComandParameterPrm としてスクリプト内で扱えます。

この例ではクリック時にウィンドウを最大化させます。

<Window Name="wnd">
  <Button Command="{script:ScriptCommand 'Prm.WindowState = WindowState.Maximized'}"
          CommandParameter="{Binding ElementName=wnd}" />
</Window>

ScriptConverter

変換前の値を Value としてスクリプト内で扱えます。

この例ではウィンドウが最大化しているときにボタンを無効にします。

<Window Name="wnd">
  <Button IsEnabled="{Binding ElementName=wnd,
                              Path=WindowState,
                              Converter={script:ScriptConverter 'Value != WindowState.Maximized'}}" />
</Window>

ScriptAction

バインドした Arg1Arg4 をスクリプト内で使えるようになってます。
ちなみに Arg0TriggerAction<>.AssociatedObject です。

この例では入力状況によってメッセージボックスの内容を変化、
さらにボタンの文字列をクリック回数によって変更しています。

<TextBox Name="tbFirstName" />
<TextBox Name="tbFamilyName" />
<Button Content="Click">
  <i:Interaction.Triggers>
    <i:EventTrigger EventName="Click">
      <script:ScriptAction Arg1="{Binding ElementName=tbFirstName}"
                           Arg2="{Binding ElementName=tbFamilyName}">
        static int i = 0;
        Arg0.Content = string.Format("Clicked ({0})", ++i);

        if (string.IsNullOrWhiteSpace(Arg1.Text))
        {
          MessageBox.Show("Please enter your first name.");
          Arg1.Focus();
        }
        else if (string.IsNullOrWhiteSpace(Arg2.Text))
        {
          MessageBox.Show("Please enter your family name.");
          Arg2.Focus();
        }
        else
        {
          MessageBox.Show(string.Format("Hello {0} {1}!!", Arg1.Text, Arg2.Text));
        }
      </script:ScriptAction>
    </i:EventTrigger>
  </i:Interaction.Triggers>
</Button>
2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?