「東雲 忠太郎」の平凡な日常のできごと

「東雲 忠太郎」の平凡な日常のできごと

2024.03.14
XML
カテゴリ: C#.NET


以下は、C#WPFで`Page`に`DataContext`を設定するサンプルコードです。


まず、`DataContext`となるクラスを定義します。


```csharp

using System.ComponentModel;


public class MyData : INotifyPropertyChanged

{

    private string message;


    public string Message

    {

        get { return message; }

        set

        {

            if (message != value)

            {

                message = value;

                OnPropertyChanged(nameof(Message));

            }

        }

    }


    public event PropertyChangedEventHandler PropertyChanged;


    protected virtual void OnPropertyChanged(string propertyName)

    {

        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

    }

}

```


次に、`Page`を作成し、その`DataContext`を`MyData`クラスのインスタンスに設定します。


```xml

<!-- MyPage.xaml -->

<Page x:Class="WpfApp.MyPage"

      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Grid>

        <TextBlock Text="{Binding Message}" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="24"/>

    </Grid>

</Page>

```


```csharp

// MyPage.xaml.cs

using System.Windows.Controls;


namespace WpfApp

{

    public partial class MyPage : Page

    {

        public MyPage()

        {

            InitializeComponent();


            // DataContextにMyDataクラスのインスタンスを設定

            DataContext = new MyData

            {

                Message = "Hello, WPF!"

            };

        }

    }

}

```


これで、`MyPage`の`TextBlock`が`MyData`クラスの`Message`プロパティにバインドされ、"Hello, WPF!"と表示されます。


また、XAMLファイルで直接`DataContext`を指定することもできます。


```xml

<!-- MyPage.xaml -->

<Page x:Class="WpfApp.MyPage"

      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

      xmlns:local="clr-namespace:WpfApp"

      DataContext="{x:Static local:MyStaticData}">

    <Grid>

        <TextBlock Text="{Binding Message}" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="24"/>

    </Grid>

</Page>

```


`MyStaticData`は、`MyData`のインスタンスを静的プロパティとして提供するクラスです。






お気に入りの記事を「いいね!」で応援しよう

Last updated  2024.03.14 05:00:49


【毎日開催】
15記事にいいね!で1ポイント
10秒滞在
いいね! -- / --
おめでとうございます!
ミッションを達成しました。
※「ポイントを獲得する」ボタンを押すと広告が表示されます。
x

© Rakuten Group, Inc.
Create a Mobile Website
スマートフォン版を閲覧 | PC版を閲覧
Share by: