Reputation: 508
I've got this basic WPF, I've done for practice, it's a sort of scorekeeping app, and I want to enter a number into a textbox, process it, and then put out the result in the label, but I cant figure out how to access them in the c# side. Here's the 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>
I want to enter a number in Number
and after processing it, I want the current score to be displayed in PlayerScore
Edit: I haven't worked in the C# code on this one, and I would also appreciate it if anyone could tell me where I could do some more reading on this subject, so that I can do more advanced things, and be able to work with other controls.
Upvotes: 0
Views: 1359
Reputation: 137128
You can do this by targeting the label at the textbox:
<TextBox x:Name="Number" ... />
<Label x:Name="PlayerName" Target="{Binding ElementName=Number}" ... />
This way you don't have to do anything in the C# to get the label to update.
To process the input you should ideally use something like MVVM (Model View ViewModel) and binding to get the value into C#, but as you are just learning you could just edit the code behind. IN the TextBox_TextChanged
method you can get access to the text through the Text
property:
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
}
}
Upvotes: 1