4
4

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

【C#/UWP】{x:Bind} と {Binding} の違い

Last updated at Posted at 2020-06-20

#{x:Bind}

画面内のコントロール間で入力を同期させたい場合や、1画面で完結するアプリケーションで使用します。
バインドしている値が変更されても、すぐに画面が変更されるわけではありません。画面の更新をしたい場合は、Bindings.Update()を呼びます。

使用例
SampleData.csSamplePage.xaml.cs 内でインスタンスを生成しています。
一画面で完結するアプリケーションの場合、画面が破棄されないのでインスタンスも破棄されません。

SamplePage.xaml
<Page>
    <!--...省略-->
    <Grid>
        <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
            <!--SampleDataのプロパティをバインディング-->
            <Slider x:Name="Slider1" Value="{x:Bind SampleData.SliderValue, Mode=TwoWay}"/>

            <!--コントロール(Slider1)のプロパティを直接バインディング-->
            <Slider x:Name="Slider2" Value="{x:Bind Slider1.Value, Mode=TwoWay}"/>
        </StackPanel>
    </Grid>
</Page>

Null値の設定

null.xaml
<!--参照したプロパティの値がnullの場合、TargetNullValueの値を使う-->
<TextBox Text="{x:Bind SampleData.NullData, TargetNullValue='(null)'}"/>

#{Binding}

DataContext(Resource)を追加して、それを参照する場合に使用します。
例えば、画面間でデータを受け渡す場合や、ナビゲーターなどによって画面の内容を差し替える場合です。
または、コントロールの内容を動的に変化させたい場合にも使用します。

使用例

  1. データを保持するオブジェクト(HogeData.csなど)を作成します。
  2. そのインスタンスをApp.xamlに作成します。(アプリケーション起動時に一回だけ作成されます)
  3. 画面が切り替わるタイミングで、HogeData.csの内容を更新します。
  4. 参照したい画面にバインドします。
1)HogeData.cs
public class HogeData : INotifyPropertyChanged {
    private string _text = "Default";
    public string HogeText {
        get => _text;
        set {
            if (_text == value) return;
            _text = value;
            // データを更新したことを通知する
            this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(HogeText)));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}
2)App.xaml
<Application
    x:Class="TemplateApp.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Application.Resources>
        <!--xmlnsは、HogeData.csの名前空間-->
        <HogeData xmlns="using:TemplateApp.Datas" x:Key="HogeDataInstance"/>
    </Application.Resources>
</Application>
3)Hoge.cs
// 例えば、ナビゲーターの項目を押したタイミングで、HogeDataの内容を更新する
var hogeData = Application.Current.Resources["HogeDataInstance"] as HogeData;
hogeData.HogeText = "hogehoge";
4)Page.xaml
<Page
    ...省略
    DataContext="{StaticResource HogeDataInstance}"
    mc:Ignorable="d">

    <Grid>
        <Button Content="{Binding HogeText, Mode=OneWay}"/>
    </Grid>
</Page>

動的にコントロールの値を変更する

sample.xaml
<!--動的にコントロールの値を変更する-->
<!--RelativeSourceは、相対的にプロパティを指定する方法-->
<TextBox Text="cyan" Background="{Binding Text, RelativeSource={RelativeSource Self},
         UpdateSourceTrigger=PropertyChanged}"/>

Null値の設定

null.xaml
<!--参照したリソースがなかった場合、FallbackValueの値を使う-->
<TextBox Text="{Binding Path=NoWhere, FallbackValue='(not bound)'}"/>

#Mode

バインディングするときにModeを設定できます。

Mode 説明
OneWay データが画面へ反映されます
(Bindingの規定値)
TwoWay データが画面へ、画面からデータ(オブジェクト)へ双方向に反映されます
OneTime バインドが確立したときに一度だけ、データが画面へ反映されます
(x:Bindの規定値)

#参考

UWPアプリ開発101 第2版:WindowsForms開発者のためのC#/XAMLによるUWPアプリ開発入門(VisualStudio2017対応版) (BluewaterSoft) Kindle版

4
4
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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?