4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

WPF/TextBlockの表示内容を変更したい

Last updated at Posted at 2019-06-27

メモ

WPFで以下のようなxamlで定義されたTextBlockの表示内容を変更したいとき,
<TextBlock>に x:Name="textBlock" などの名前をつけておく.
その名前でxaml.csにおいて参照できる.

ツールボックスからドラッグドロップで追加しただけでは
<TextBlock> にx:Nameの属性が設定されず,xaml.cs内で参照できなかったのでメモ

MainWindow.xaml
<Window x:Class="WpfApp4.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:WpfApp4"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Button Content="ボタン1" HorizontalAlignment="Center" VerticalAlignment="Center" Width="150" Height="30" Click="Button_Click" Margin="317,96,326.333,294.667"/>
        <TextBlock x:Name="textBlock" HorizontalAlignment="Center" Margin="317,193,164.333,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Height="105" Width="312" FontSize="22"/>
    </Grid>
</Window>
MainWindow.xaml.cs
using System.Windows;

namespace WpfApp4
{
    /// <summary>
    /// MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            textBlock.Text = "ボタン1が押されました.";//.xamlで宣言した名前で参照
        }
    }
}
4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?