[英]Wpf Textbox and label text access in c#
我已經有了這個基本的WPF,我已經進行了練習,它是一種記分應用程序,我想在文本框中輸入數字,進行處理,然后將結果放入標簽中,但是我無法確定了解如何在c#端訪問它們。 這是XAML:
<StackPanel HorizontalAlignment="Right" VerticalAlignment="Stretch">
<Label Name="PlayerName" Style="{StaticResource PlayerName}"/>
<Label Name="PlayerScore" Style="{StaticResource Score}"/>
<ScrollViewer Height="380">
</ScrollViewer>
</StackPanel>
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Top">
<TextBox Name="Number" MaxLength="3" Width="160" Margin="20" FontSize="30" TextChanged="TextBox_TextChanged"></TextBox>
<Button IsDefault="True" Style="{StaticResource Golden} " Click="Button_Click">Запиши резултат</Button>
<Button Style="{StaticResource Golden}">Върни назад</Button>
</StackPanel>
我想在Number
輸入一個數字,並在對其進行處理后,希望將當前分數顯示在PlayerScore
編輯:我還沒有使用C#代碼編寫代碼,如果有人可以告訴我我可以在該主題上做更多的閱讀,以便可以做更高級的事情,並且能夠與其他控件一起使用。
您可以通過在文本框中定位標簽來做到這一點:
<TextBox x:Name="Number" ... />
<Label x:Name="PlayerName" Target="{Binding ElementName=Number}" ... />
這樣,您無需在C#中執行任何操作即可更新標簽。
要處理輸入,理想情況下,您應該使用諸如MVVM(模型視圖ViewModel)和綁定之類的東西來將值輸入C#中,但是由於您只是在學習, 就可以編輯后面的代碼。 在TextBox_TextChanged
方法中,您可以通過Text
屬性訪問Text
:
private void TextBox_TextChanged(object sender, EventArgs e)
{
var textBox = (TextBox)sender;
int score;
if (TryParse(textBox.Text, out score))
{
// Value entered was an integer, process it
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.