在WPF应用程序中将字符串输入转换为double

时间:2015-09-15 16:11:39

标签: c# .net wpf

<Window x:Class="MySecondApplication.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MySecondApplication"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid RenderTransformOrigin="0.393,0.48">
        <TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23" Margin="175,25,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
        <TextBox x:Name="textBox1" HorizontalAlignment="Left" Height="23" Margin="175,69,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
        <Label x:Name="FirstInput" Content="First Number" HorizontalAlignment="Left" Margin="46,30,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.855,0.173" Height="23"/>
        <Label x:Name="SecondInput" Content="Second Number" HorizontalAlignment="Left" Margin="46,74,0,0" VerticalAlignment="Top"/>
        <Button x:Name="MyButton" Content="Button" HorizontalAlignment="Left" Margin="219,147,0,0" VerticalAlignment="Top" Width="76"/>
        <TextBox x:Name="result" HorizontalAlignment="Left" Height="24" Margin="190,212,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>

    </Grid>
</Window>

我是C#的初学者。我正在尝试制作一个只添加两个数字的简单计算器。我有两个文本框。现在我想转换 字符串数据类型 FirstInput SecondInput 要加倍。这是什么命令?

4 个答案:

答案 0 :(得分:2)

这应该可以解决问题,并为您提供一些验证的开始。

double firstInputDouble;

if(!double.TryParse(FirstInput.Content, out firstInputDouble)){
    // something went wrong....
}

对于你的第二个双倍重复相同的操作,然后你将以你想要的格式使用它们。

答案 1 :(得分:0)

使用tryparse来避免异常

double res;
Double.TryParse(YourString, out res);

答案 2 :(得分:0)

var firstInputAsDouble = Convert.ToDouble(FirstInput.Content);

double firstInputAsDouble;
double.TryParse(FirstInput.Content, out firstInputAsDouble);

答案 3 :(得分:0)

//creating two double variables
double FirstInput_double,SecondInput_double;
//Using the Convert.ToDouble() function to do the conversion
FirstInput_double = Convert.ToDouble(FirstInput);
SecondInput_double = Convert.ToDouble(SecondInput);
//do what you want with the double converted values