UWPはintタイプの変数をTextBlockのText属性にバインドする

3920 ワード

ButtonコントロールとTextBlockコントロールがあり、TextBlockのText属性をint属性にバインドし、ButtonボタンをクリックするたびにTextBlockのText属性の数値を1つ追加する機能が必要です.
その中でMainPage.xamlは、2つのコントロールを定義し、TextBlockのTextをResultにバインドします.
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            "*"/>
            "*"/>
        Grid.RowDefinitions>
        <Button Grid.Row="0" 
                Content="Button1"
                Click="Button_Click"
                HorizontalAlignment="Center"
                VerticalAlignment="Center"/>
        Grid.Row="1"
                   Name="TestText"
                   HorizontalAlignment="Center"
                   VerticalAlignment="Center"
                   Text="{Binding Path=Result}"/>
    Grid>

バインドソースを表示するには、Windows::UI::Xaml::Data::INotifyPropertyChangedを実装します.
public sealed partial class MainPage : Page, INotifyPropertyChanged
    {
        private int result;
        public int Result
        {
            get
            {
                return result;
            }
            set
            {
                result = value;
                OnPropertyChanged();
            }
        }
        public event PropertyChangedEventHandler PropertyChanged = delegate { };
        private void OnPropertyChanged([CallerMemberName]string propertyName = null)
        {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        public MainPage()
        {
            this.InitializeComponent();
            this.DataContext = this;
            Result = 0;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Result += 1;
        }
    }