###前提・実現したいこと
C#のWPFでUIアプリの開発を行っています。
クラスを作り、そこからtextblockなどのUIを操作したいと考えております。
以下のコードでは、ボタンを押すことでtextblockのTextが変更されることを期待していますが、思い通りになりません。
###該当のソースコード
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; 15 16namespace WpfApplication1 17{ 18 public partial class MainWindow : Window 19 { 20 public MainWindow() 21 { 22 InitializeComponent(); 23 } 24 25 class TextChange:MainWindow 26 { 27 public void Change(string x) 28 { 29 textBlock.Text = x; 30 } 31 } 32 private void button_Click(object sender, RoutedEventArgs e) 33 { 34 string ChangeTo = "Changed"; 35 TextChange hogehoge = new TextChange(); 36 hogehoge.Change(ChangeTo); 37 38 } 39 } 40}
xaml
1<Window x:Class="WpfApplication1.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:WpfApplication1" 7 mc:Ignorable="d" 8 Title="MainWindow" Height="100" Width="200"> 9 <Grid> 10 <TextBlock x:Name="textBlock" HorizontalAlignment="Left" Margin="68,10,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top"/> 11 <Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="54,36,0,0" VerticalAlignment="Top" Width="76" Click="button_Click"/> 12 13 </Grid> 14</Window>
###実行結果
ボタンを押しても何も変わりません。
また、気になる点として、実行後何もしないでウィンドウのx印で閉じるとそのままデバッグが終了しますが、
ボタンを押してからx印で閉じると、ウィンドウは消えますがデバッグが実行中になっています。
###質問事項
①上のコードでは、なぜ期待した結果にならないのか。
②どのようにすれば望んだ挙動になるのか。
その2点をお伺いしたく質問させていただきました。
###補足
バインディングでやる方法も考えたのですが、その方法だと私の望んだ回答を得られないかもしれません。
というのは、長くなるのもありこちらでは仮のプログラムとしてTextの書き換えを行っています。
クラスでグリッドなどに図形を描いたりといったことをバインディングで実装できるのでしょか…?
C#どころかプログラムに関しても初心者です。盛大な勘違いをしてるかもしれないのでご容赦ください。
回答4件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2016/09/15 09:19