在文本块(UWP)上键入按钮内容

时间:2017-08-02 07:31:44

标签: c# uwp

在我的项目中,我有一个文本块

<TextBlock Name="MyDisplay" TextAlignment="Center"
           Style="{StaticResource HeaderTextBlockStyle}"/>

画布中的一组按钮

<Canvas Name="ButtonPanel">
                <Button Style="{StaticResource MyButtonStyle}" Content="1" Canvas.Left="0" Canvas.Top="0"/>
                <Button Style="{StaticResource MyButtonStyle}" Content="2" Canvas.Left="100" Canvas.Top="0"/>
                <Button Style="{StaticResource MyButtonStyle}" Content="3" Canvas.Left="200" Canvas.Top="0"/>
                <Button Style="{StaticResource MyButtonStyle}" Content="4" Canvas.Top="86" Canvas.Left="0"/>
                <Button Style="{StaticResource MyButtonStyle}" Content="5" Canvas.Top="86" Canvas.Left="100"/> </Canvas>

我想在文本块中编写按钮内容

我的代码是

public DisplayPad()
{
   this.InitializeComponent();
   ButtonPanel.AddHandler(PointerPressedEvent, new PointerEventHandler(ScreenMarkup_PointerPressed), true);

   UpdateDisplay();
}

public void ScreenMarkup_PointerPressed(object sender, RoutedEventArgs e)
{
   Button button = e.OriginalSource as Button;
   if (button == null)
   return;
   string content = button.Content.ToString();            
   double digit;
   if (double.TryParse(content, out digit))            
   {
      if(content == "1")
      {
         //codes
         MyDisplay.Text = "1";
      }
   }
   UpdateDisplay();
}

    void UpdateDisplay()
    {
        try
        {
            MyDisplay.Foreground = Application.Current.Resources["ApplicationForegroundThemeBrush"] as Brush;
            // Update the display 
            MyDisplay.Text = String.Format("{0:##.##}");                
        }
        catch
        {
            //Exception
        }
    }

但是这段代码不起作用,它不是TextBlock中的更新号。

但在Windows Phone 8中使用同样的东西,它工作正常但只是代码差异(Windows phone 8 code)

public DisplayPad()
{
    this.InitializeComponent();
    ButtonPanel.AddHandler(Button.MouseLeftButtonUpEvent, new MouseButtonEventHandler(ScreenMarkupButton_MouseLeftButtonUp), true);

    UpdateDisplay();
}

    public void ScreenMarkupButton_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
       Button button = e.OriginalSource as Button;
       if (button == null)
       return;
       string content = button.Content.ToString();            
       double digit;
       if (double.TryParse(content, out digit))            
       {
          //My Codes
       }
       UpdateDisplay();
    }

1 个答案:

答案 0 :(得分:1)

OriginalSource对象不是Button,而是TextBlock中的内部Button,因此您需要将代码更改为

var textBlock = e.OriginalSource as TextBlock;
if (textBlock == null)
    return;
string content = textBlock.Text;