将文本框中输入的数字数据绑定到后面代码中的变量

Databind entered number in textbox to a variable in code behind

我有一个弹出窗口 window,其中包含一个允许用户输入数字的文本框,然后单击关闭 window 的按钮。如何将用户输入的内容绑定到后面代码中的双精度变量?

例如在我的弹出窗口 window 我有:

<TextBox Text="{Binding ...., ElementName ....}" Margin="3" />

<Button Content="close" Click="Close_Popup" HorizontalAlignment="Center" />

我想将该文本框中输入的任何内容绑定到后面代码中名为 "double example;" 的变量。

这是正确的做法吗?或者当我关闭 window?

时变量会返回 null
int anInteger;
anInteger = Convert.ToInt32(textBox1.Text);

这是我的 xaml 弹出 window:

    x:Name="this"
    Title="Scale"
    WindowStartupLocation="CenterOwner"
    ResizeMode="NoResize">
 <StackPanel Orientation="Vertical">
    <TextBlock Text="Enter the distance between these two points in meters:" Margin="3"/>
    <TextBox Text="{Binding userInput.get, ElementName=this}" x:Name="scaleText_Box" Margin="3"/>
    <Button Content="Done" Click="closeScale_Window" Width="100" Margin="10"/>
 </StackPanel>

这是我的弹出窗口背后的代码 window:

public partial class ScaleInputWindow : Window
{
    public ScaleInputWindow()
    {
        InitializeComponent();
    }

    public double userInput { get; set; }

    private void closeScale_Window(object sender, RoutedEventArgs e)
    {
        this.DialogResult = true;
    }
}

这是我的主要代码 window.cs,userInput 是开头声明的双精度值。

ScaleInputWindow scaleInput = new ScaleInputWindow();
if (scaleInput.ShowDialog() == true)
{
    userInput = scaleInput.Input;
}

根据您的代码 anInteger 将在您关闭 window

后立即为 0

您可以在项目的单独 class 中声明一个静态变量,并在项目的任何地方访问它。

 public class Popvalue
 {
    public static int anInteger = 0;
 }

然后在您的弹出窗口中 window 为其分配值。

  Popvalue.anInteger = Convert.ToInt32(textBox1.Text);

我建议使用 ShowDialog 方法来显示弹出窗口 window。

在您的 pop-window 代码中,创建一个包含该值的 属性。 (您可以将此绑定到您的 TextBox.Text 属性)

public int anInteger {get; set;}

然后当用户关闭window(或单击确定按钮)时,设置DialogResult 属性(对所有windows可用)

private void btnDialogOk_Click(object sender, RoutedEventArgs e)
{
   this.DialogResult = true;
}

请注意,设置 DialogResult 会自动关闭弹出窗口 window。

要使用您的 window 并获得结果...

MyPopupWindow popup = new MyPopupWindow ();

if(popup.ShowDialog() == true)
    enteredNumber = popup.anInteger;

您没有包含 get

<TextBox Text="{Binding ElementName=this, Path=userInput}" x:Name="scaleText_Box" Margin="3"/>

您也可以只设置 DataContext 然后不设置 ElementName=this
DataContext 更常见