こんにちは
現在、C#WPFを勉強中の初心者です。
テキストボックスに入力したテキストを変更ボタンをクリックしたときに、
testmessageというテキストに変更されるようにしたいです。
調べてみたところINotifyPropertyChangedを実装すれば変更通知を渡せるということで
MSDNのサンプルコードを参考にコーディングしてみました。
しかし、button1_Click内のコードをどのように記述したらよいのかがわかっていません。
どのように記述したらよいのか教えていただけないでしょうか。
コード例を提示していただけたら非常にありがたいです。
XAML
1<Window x:Class="Sample1.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:Sample1" 7 mc:Ignorable="d" 8 Title="MainWindow" Height="124" Width="525"> 9 <Grid> 10 <TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23" Margin="10,10,0,0" TextWrapping="Wrap" Text="{Binding Message}" VerticalAlignment="Top" Width="327"/> 11 <Button x:Name="button" Content="表示" HorizontalAlignment="Left" Margin="10,49,0,0" VerticalAlignment="Top" Width="75" Click="button_Click"/> 12 <Button x:Name="button1" Content="変更" HorizontalAlignment="Left" Margin="111,49,0,0" VerticalAlignment="Top" Width="75" Click="button1_Click"/> 13 14 </Grid> 15</Window> 16
C#
1using System; 2using System.Collections.Generic; 3using System.Linq; 4using System.Text; 5using System.Threading.Tasks; 6using System.Windows; 7using System.Windows.Controls; 8using System.Windows.Data; 9using System.Windows.Documents; 10using System.Windows.Input; 11using System.Windows.Media; 12using System.Windows.Media.Imaging; 13using System.Windows.Navigation; 14using System.Windows.Shapes; 15using System.Runtime.CompilerServices; 16using System.ComponentModel; 17 18namespace Sample1 19{ 20 /// <summary> 21 /// MainWindow.xaml の相互作用ロジック 22 /// </summary> 23 public partial class MainWindow : Window 24 { 25 public string Message { get; set; } 26 public string TextMessage { get; private set; } 27 28 public MainWindow() 29 { 30 InitializeComponent(); 31 32 this.DataContext = this; 33 } 34 35 private void button_Click(object sender, RoutedEventArgs e) 36 { 37 MessageBox.Show(Message); 38 } 39 40 private void button1_Click(object sender, RoutedEventArgs e) 41 { 42 //Message = "testmessage"; 43 MessageBox.Show(TextMessage); 44 } 45 46 public class ChangeText : INotifyPropertyChanged 47 { 48 private string TextValue = String.Empty; 49 50 public event PropertyChangedEventHandler PropertyChanged; 51 52 private void NotifyPropertyChanged([CallerMemberName] String propertyName = "") 53 { 54 if (PropertyChanged != null) 55 { 56 PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 57 } 58 } 59 60 private ChangeText() 61 { 62 TextValue = "testmessage"; 63 } 64 65 public string TextMessage 66 { 67 get 68 { 69 return this.TextValue; 70 } 71 72 set 73 { 74 if (value != this.TextValue) 75 { 76 this.TextValue = value; 77 NotifyPropertyChanged(); 78 } 79 } 80 } 81 82 } 83 } 84}

バッドをするには、ログインかつ
こちらの条件を満たす必要があります。