###概要
wpfを使うにあたって、自動実装プロパティというものを避けて通れないということがわかってきました。このようなものです。
public string Hoge { get; set; }
このget;set;がどのような動きをしているかわかりません。
サンプルはいかになります。一方のテキストボックスの内容が、もう一方のテキストボックス内でも同期されるというものです。
想像なんですが、Hoge { get; set; }という部分の、Hogeという変数(?)はxaml内ではテキストボックスのプロパティとして存在し、mainwindow.xaml.cs内には変数として存在します。
mainwindow.xamal.cs内の変数をgetし、xaml内のプロパティにsetするという意味かと感じるのですが、違うでしょうか?
アドバイスお願いします。
###mainwindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace test_binding
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
public MainWindow() { InitializeComponent(); //クラスのインスタンス HogeClass HogeObject = new HogeClass(); HogeObject.Hoge = "Try it."; stackpanel.DataContext = HogeObject; } public class HogeClass { public string Hoge { get; set; } } }
}
###xaml
<Window x:Class="test_binding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:test_binding"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800" Loaded="Window_Loaded">
<StackPanel Name="stackpanel">
<TextBox Name="textbox1" Text="{Binding Hoge, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="10" />
<TextBox Name="textbox2" Text="{Binding Hoge, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="10" />
</StackPanel>
</Window>
###参考にしたサイト
https://water2litter.net/gin/?p=1401
回答1件
あなたの回答
tips
プレビュー