简体   繁体   English

C#中的WPF文本框和标签文本访问

[英]Wpf Textbox and label text access in c#

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. 我已经有了这个基本的WPF,我已经进行了练习,它是一种记分应用程序,我想在文本框中输入数字,进行处理,然后将结果放入标签中,但是我无法确定了解如何在c#端访问它们。 Here's the XAML: 这是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 我想在Number输入一个数字,并在对其进行处理后,希望将当前分数显示在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. 编辑:我还没有使用C#代码编写代码,如果有人可以告诉我我可以在该主题上做更多的阅读,以便可以做更高级的事情,并且能够与其他控件一起使用。

You can do this by targeting the label at the textbox: 您可以通过在文本框中定位标签来做到这一点:

<TextBox x:Name="Number" ... />

<Label x:Name="PlayerName" Target="{Binding ElementName=Number}" ... />

MSDN Page MSDN页面

This way you don't have to do anything in the C# to get the label to update. 这样,您无需在C#中执行任何操作即可更新标签。

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. 要处理输入,理想情况下,您应该使用诸如MVVM(模型视图ViewModel)和绑定之类的东西来将值输入C#中,但是由于您只是在学习, 就可以编辑后面的代码。 IN the TextBox_TextChanged method you can get access to the text through the Text property: 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM