Home > Mobile >  How to update textblock with method
How to update textblock with method

Time:11-01

I have a textbox that provide user to input string. how can i pass that string to method and toUpper() it. and pass back the string to textblock in the main window that both of the box and block update in real time?

For my C# code:

public MainWindow()
    {
        InitializeComponent();

    }
private  void TextBox_TextChanged(object sender, TextChangedEventArgs e)
    {

        textBlock.Text = textBox.Text  "changed";
        
        
    }

it is just as simple like this.

for my xaml code:

<Grid >
    
   
    <TextBox x:Name ="textBox" HorizontalAlignment="Left" Height="105" Margin="28,185,0,0" TextWrapping="Wrap" Text="HELLO" VerticalAlignment="Top" Width="300" TextChanged="TextBox_TextChanged"/>
    <TextBlock x:Name="textBlock" HorizontalAlignment="Left" Height="116" Margin="114,40,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="328"/>
</Grid>

i want to know why the text of my textblock cannot be updated when i type something inside the textbox.

CodePudding user response:

Do you need something like this?

private  void TextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        textBox.Text = textBox.Text?.ToUpper();
        textBlock.Text = textBox.Text;
        textBox.CaretIndex = textBox.Text?.Length ?? 0; //You need this to continue typing from the last index onwards..
        
    }

I don't exactly understand if you need both the textBox and the textBlock to change at the same time or only the textBlock to be in UpperCase, but the concept is the same

CodePudding user response:

I combined the answer of @Yavor Georgiev

You are encountering a null reference exception. When the textBox control is created it will trigger the textChange event on textBox and by that point, textBlock isn't created and is therefore null. You can just change the order of the textboxes in the XAML and you will be fine.

Change the order

Grid>
    <TextBlock x:Name="textBlock" HorizontalAlignment="Left" Height="116" Margin="114,40,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="328"/>
    <TextBox x:Name ="textBox" HorizontalAlignment="Left" Height="105" Margin="28,185,0,0" TextWrapping="Wrap" Text="HELLO" VerticalAlignment="Top" Width="300" TextChanged="TextBox_TextChanged"/>
   
</Grid>

For the upper part i used @Yavor Georgiev answer when typing

  private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        textBox.Text = textBox.Text?.ToUpper();
        textBlock.Text = textBox.Text;
        textBox.CaretIndex = textBox.Text?.Length ?? 0; 
        textBlock.Text = textBox.Text   "changed";           
    }
  • Related