Bindingで実現する最小限のサンプルです。
XAML側
xml
1 <Grid x:Name="maingrid">
2 <Grid.RowDefinitions>
3 <RowDefinition />
4 <RowDefinition />
5 <RowDefinition />
6 </Grid.RowDefinitions>
7 <TextBox Grid.Row="0" Text="{Binding Texts[0], Mode=OneWay}" />
8 <TextBox Grid.Row="1" Text="{Binding Texts[1], Mode=OneWay}" />
9 <TextBox Grid.Row="2" Text="{Binding Texts[2], Mode=OneWay}" />
10 </Grid>
cs側
C#
1public partial class MainWindow : Window
2{
3 public MainWindow()
4 {
5 InitializeComponent();
6
7 //GridのDataContextを設定
8 this.maingrid.DataContext = new GridContext();
9 }
10}
11
12public class GridContext
13{
14 public string[] Texts { get; private set; }
15
16 public GridContext()
17 {
18 this.Texts = new[] { "01text", "02text", "03text" };
19 }
20}
21
- DataContextはTextBox自体に設定することも、上位のWindowに設定することもできます。
(より下位のものが優先されます。この例では TextBox > Grid > Window )
- 上のサンプルでは、DataContext設定時に、1回限り、配列の内容がTextBoxに反映されます。
その後もTextsプロパティが変わる度にTextBoxへ自動反映したい場合は、
DataContextとなっているオブジェクト側でINotifyPropertyChangedを実装し、
プロパティの変更を画面へ通知してやる必要があります。
これも一応サンプル載せておきます。
C#
1public class GridContext : INotifyPropertyChanged
2{
3 public event PropertyChangedEventHandler PropertyChanged;
4
5 private string[] _texts;
6
7 public string[] Texts
8 {
9 get
10 {
11 return _texts;
12 }
13 private set
14 {
15 _texts = value;
16
17 //画面への更新通知
18 PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Texts)));
19 }
20 }
21
22 public GridContext()
23 {
24 this.Texts = new[] { "01text", "02text", "03text" };
25 }
26}
- 若干ややこしいんですが、上記のように更新通知を実装した場合でも、配列の要素の変更は検知できません。
Textsプロパティを更新する場合は、 Texts[0] = hoge
のようにせずに、配列自体をまるごと作り直す必要があります。
(あるいはObservableCollectionのようにINotifyCollectionChangedを実装したコレクションを使います)
- TextBoxでの入力内容変更を配列側に反映したい場合は、Binding Modeを
Mode=TwoWay
に変更し、
プロパティ側のsetの private
を削除します。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。