我有一個文本框,為用戶提供輸入字串。我怎樣才能將該字串傳遞給方法和 toUpper() 它。并將字串傳回主視窗中的文本塊,框和塊都實時更新?
對于我的 C# 代碼:
public MainWindow()
{
InitializeComponent();
}
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
textBlock.Text = textBox.Text "changed";
}
就這么簡單。
對于我的 xaml 代碼:
<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>
我想知道為什么當我在文本框中鍵入內容時無法更新我的文本塊的文本。
uj5u.com熱心網友回復:
你需要這樣的東西嗎?
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..
}
我不完全明白您是需要 thetextBox和 thetextBlock同時改變還是只textBlock需要 in UpperCase,但概念是一樣的
uj5u.com熱心網友回復:
我結合了@Yavor Georgiev的答案
您遇到空參考例外。當創建 textBox 控制元件時,它將觸發 textBox 上的 textChange 事件,此時,textBlock 未創建,因此為 null。您只需更改 XAML 中文本框的順序就可以了。
更改順序
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>
對于上半部分,我在打字時使用了 @Yavor Georgiev 答案
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";
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/342838.html
上一篇:Postgres生成錯誤的id
下一篇:如何在子類方法中使用父類變數名
