WPFでBindingしているTextBoxにプログラムで値を入れても表示されない

実現したいこと

前提

TextBoxにプログラムで値を入れたいのですが、表示されません。
Bindingを外せば表示されますが、Bindingしたまま表示させたいです。

発生している問題・エラーメッセージ

空白になってしまいます。

該当のソースコード

XAML

1<Window x:Class="WpfApp_Binding.MainWindow" 2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 4 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 5 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 6 xmlns:local="clr-namespace:WpfApp_Binding" 7 mc:Ignorable="d" 8 Title="MainWindow" Height="450" Width="800"> 9 <Grid> 10 <StackPanel Orientation="Vertical"> 11 <!-- TextBox x:Name="Text1" /> 12 <TextBox x:Name="Text2" / --> 13 <TextBox x:Name="Text1" Text="{Binding text1,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/> 14 <TextBox x:Name="Text2" Text="{Binding text2,Mode=TwoWay,UpdateSourceTrigger=Explicit}"/> 15 </StackPanel> 16 </Grid> 17</Window>

C#

1using System.Windows;2using System.Windows.Controls;3using System.Windows.Data;4 5namespace WpfApp_Binding 6{7 public partial class MainWindow : Window 8 {9 public MainWindow()10 {11 InitializeComponent();12 DataContext = new MyViewModel();13 14 Text1.Text = "test1";15 Text2.Text = "test2";16 17 BindingExpression be;18 be = Text1.GetBindingExpression(TextBox.TextProperty);19 be.UpdateSource();20 be = Text2.GetBindingExpression(TextBox.TextProperty);21 be.UpdateSource(); 22 }23 }24 25 // DataContext26 public class MyViewModel : INotifyPropertyChanged 27 {28 private string _text1;29 public string Text1 30 {31 get { return _text1; }32 set 33 {34 if (_text1 != value)35 {36 _text1 = value;37 OnPropertyChanged("Text1");38 }39 }40 }41 42 private string _text2;43 public string Text2 44 {45 get { return _text2; }46 set 47 {48 if (_text2 != value)49 {50 _text2 = value;51 OnPropertyChanged("Text2");52 }53 }54 }55 56 public event PropertyChangedEventHandler PropertyChanged;57 58 protected void OnPropertyChanged(string propertyName)59 {60 PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));61 }62 }63}

試したこと

Bindingが無い状態なら表示されました。
GetBindingExpressionを使ってみましたが、表示されませんでした。

補足情報(FW/ツールのバージョンなど)

.NET Framework 4.7.2

コメントを投稿

0 コメント