WPF / C#文本框中的数字是动态计算的

如何解决WPF / C#文本框中的数字是动态计算的

|| 好的,因此,我可以肯定我在使用此小型应用程序的过程中步入正轨,但请告诉我。用户在4个可编辑文本框中输入4个数字中的3个,然后自动计算缺少的数字。此处的应用图片: http://www.peauproductions.com/images/lens_app.PNG 我研究了数据绑定,我认为我需要使值能够全局更改。我希望这些值能够动态更新/计算,而不必具有“计算”按钮。 一旦开始运行,我需要执行验证检查以确保仅输入布尔值(无文本),并弹出工具提示说要输入数字。 立即获得以下错误: \“ \'设置属性\'System.Windows.Controls.TextBox.Text \'引发异常。\'行号\ '56 \'和行位置\ '51 \'。\” MainWindow.xaml代码:
<Window x:Class=\"ConverterApp.MainWindow\"
    xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"
    xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"
    Title=\"ConverterApp\" Height=\"360\" Width=\"280\"
    xmlns:c=\"clr-namespace:ConvertorApp;assembly=\">

<Grid>
    <!--Outer Box + Title-->
    <TextBox Height=\"309\" Width=\"248\"
    Text=\" Lens Calculator\"
    IsReadOnly=\"True\" 
    Margin=\"5,5,0\"
    VerticalAlignment=\"Top\"
    HorizontalAlignment=\"Left\"
    BorderThickness=\"2.0\"
    FontSize=\"16\" FontFamily=\"Verdana\" FontWeight=\"Bold\">
        <TextBox.BorderBrush>
            <LinearGradientBrush StartPoint=\"0,0\" EndPoint=\"1,1\" >
                <GradientStop Color=\"Black\" Offset=\"0\" />
            </LinearGradientBrush>
        </TextBox.BorderBrush> 
    </TextBox>

    <!--Title Text-->
    <TextBox Height=\"50\" Width=\"230\"
    Text=\"Enter Image Width,Length and Either Distance or Lens Values Below\"
    IsReadOnly=\"True\" 
    Margin=\"14,29,0\"
    TextWrapping=\"Wrap\"
    VerticalAlignment=\"Top\"
    HorizontalAlignment=\"Left\"
    FontSize=\"12\" FontFamily=\"Verdana\"  FontStyle=\"Italic\"
    BorderThickness=\"0\">        
    </TextBox>

    <TextBox Height=\"20\" Width=\"230\"
    Text=\"Must Be Same Units (in,ft,cm,mm)\"
    IsReadOnly=\"True\" 
    Margin=\"14,59,0\"
    VerticalAlignment=\"Top\"
    HorizontalAlignment=\"Left\"
    FontSize=\"10\" FontFamily=\"Verdana\" FontStyle=\"Italic\"
    BorderThickness=\"0\">
    </TextBox>

    <!--Distance-->
    <TextBox Height=\"20\" Width=\"105\"
    Text=\"Distance/Height:\"
    IsReadOnly=\"True\" 
    Margin=\"15,80,0\"
    VerticalAlignment=\"Top\"
    HorizontalAlignment=\"Left\"
    FontFamily=\"Verdana\"
    BorderThickness=\"0\">
    </TextBox>

    <TextBox x:Name=\"DistanceBox\" Height=\"20\" Width=\"50\"
    Text=\"{x:Static c:Variables.DistanceBox}\"
    Margin=\"125,0\"
    MaxLength=\"5\" 
    VerticalAlignment=\"Top\"
    HorizontalAlignment=\"Left\"
    FontFamily=\"Verdana\">
        <TextBox.BorderBrush>
            <LinearGradientBrush StartPoint=\"0,1\" >
                <GradientStop Color=\"Black\" Offset=\"0\" />
            </LinearGradientBrush>
        </TextBox.BorderBrush>
    </TextBox>

    <!--Image Width-->
    <TextBox Height=\"20\" Width=\"90\"
    Text=\"Image Width:\"
    IsReadOnly=\"True\" 
    Margin=\"15,105,0\"
    VerticalAlignment=\"Top\"
    HorizontalAlignment=\"Left\"
    FontFamily=\"Verdana\"
    BorderThickness=\"0\">
    </TextBox>

    <TextBox x:Name=\"WidthBox\" Height=\"20\" Width=\"50\"
    Text=\"{x:Static c:Variables.WidthBox}\"
    Margin=\"125,0\"
    MaxLength=\"5\" 
    VerticalAlignment=\"Top\"
    HorizontalAlignment=\"Left\"
             FontFamily=\"Verdana\">
        <TextBox.BorderBrush>
            <LinearGradientBrush StartPoint=\"0,1\" >
                <GradientStop Color=\"Black\" Offset=\"0\" />
            </LinearGradientBrush>
        </TextBox.BorderBrush>
    </TextBox>

    <!--Image Length-->
    <TextBox Width=\"95\"
    Text=\"Image Length:\"
    IsReadOnly=\"True\" 
    Margin=\"15,130,161\" HorizontalAlignment=\"Left\"
    FontFamily=\"Verdana\"
    BorderThickness=\"0\">
    </TextBox>

    <TextBox x:Name=\"LengthBox\" Height=\"20\" Width=\"50\"
    Text=\"{x:Static c:Variables.LengthBox}\"
    Margin=\"125,0\"
             MaxLength=\"5\" 
    VerticalAlignment=\"Top\"
    HorizontalAlignment=\"Left\"
             FontFamily=\"Verdana\">
        <TextBox.BorderBrush>
            <LinearGradientBrush StartPoint=\"0,1\" >
                <GradientStop Color=\"Black\" Offset=\"0\" />
            </LinearGradientBrush>
        </TextBox.BorderBrush>
    </TextBox>

    <!--Lens Needed-->
    <TextBox Height=\"20\" Width=\"90\"
    Text=\"Lens (mm):\"
    IsReadOnly=\"True\" 
    Margin=\"15,155,0\"
    VerticalAlignment=\"Top\"
    HorizontalAlignment=\"Left\"
    FontFamily=\"Verdana\"
    BorderThickness=\"0\">
    </TextBox>

    <TextBox x:Name=\"LensNeeded\" Height=\"20\" Width=\"50\"
    Text=\"{x:Static c:Variables.LensNeeded}\"
    Margin=\"125,0\"
             MaxLength=\"4\" 
    VerticalAlignment=\"Top\"
    HorizontalAlignment=\"Left\"
             FontFamily=\"Verdana\">
        <TextBox.BorderBrush>
            <LinearGradientBrush StartPoint=\"0,1\" >
                <GradientStop Color=\"Black\" Offset=\"0\" />
            </LinearGradientBrush>
        </TextBox.BorderBrush>
    </TextBox>

    <!--Info-->
    <TextBox Height=\"70\" Width=\"230\"
    Text=\"The lens focal length value represents the estimated mm value for a 1/4 inch sensor (Playstation Eye).  A lower mm will give a wider Field of View (FOV),and a higher value less FOV. \"
    IsReadOnly=\"True\" 
    TextWrapping=\"Wrap\"
    Margin=\"15,180,0\"
    FontSize=\"11\"
    VerticalAlignment=\"Top\"
    HorizontalAlignment=\"Left\"
    FontFamily=\"Verdana\"  FontStyle=\"Italic\"
    BorderThickness=\"0\">
    </TextBox>
    <TextBox Height=\"55\" Width=\"230\"
    Text=\"It is not recommend you use a lens of less than 2.5mm focal length with image tracking software due to distortion.\"
    IsReadOnly=\"True\"
    FontSize=\"11\"
    TextWrapping=\"Wrap\"
    Margin=\"15,253,0\"
    VerticalAlignment=\"Top\"
    HorizontalAlignment=\"Left\"
    FontFamily=\"Verdana\"  FontStyle=\"Italic\"
    BorderThickness=\"0\">
    </TextBox>


</Grid>
MainWindow.xaml.cs代码:
using System;
using System.Windows;

namespace ConvertorApp
{
    public class Variables
    {
        public const double DistanceBox = 0;
        public const double WidthBox = 0;
        public const double LengthBox = 0;
        public const double LensNeeded = 0;
        public const double WidthBased = 0;
        public const double LengthBased = 0;

        public void Calc()
        {
            double WidthBased = 2.952*(DistanceBox/WidthBox);
            double LengthBased = 3.984*(DistanceBox/LengthBox);

            if (WidthBased < LengthBased)
            {
                double LensNeeded = WidthBased;
            }else{
                double LensNeeded = LengthBased;
            }
        }
    }
}
如果您可以想到一种更简单或更正确的方法来进行自己的工作,请告诉我(我刚刚开始学习WPF / C#内容)。谢谢 更新: 这是显示从下面建议的更改的后台代码:
    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;

namespace ConverterApp
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = new Variables();
        }
    }

    public class Variables : INotifyPropertyChanged
    {
        // Declare the PropertyChanged event.
        public event PropertyChangedEventHandler PropertyChanged;

        private double m_distanceBox;
        public double DistanceBox
        {
            get { return m_distanceBox; }
            set
            {
                m_distanceBox = value;
                // modify calc to read the text values
                Calc();
                // Call NotifyPropertyChanged when the source property 
                // is updated.
                NotifyPropertyChanged(\"DistanceBox\");
            }
        }

        private double m_widthBox;
        public double WidthBox
        {
            get { return m_widthBox; }
            set 
            {
                m_widthBox = value;
                // modify calc to read the text values
                Calc();
                // Call NotifyPropertyChanged when the source property 
                // is updated.
                NotifyPropertyChanged(\"WidthBox\");
            }  
        }

        private double m_lengthBox;
        public double LengthBox
        {
            get { return m_lengthBox; }
            set
            {
                m_lengthBox = value;
                // modify calc to read the text values
                Calc();
                // Call NotifyPropertyChanged when the source property 
                // is updated.
                NotifyPropertyChanged(\"LengthBox\");
            } 
        }

        private double m_lensBox;
        public double LensNeeded
        {
            get { return m_lensBox; }
            set
            {
                m_lensBox = value;
                // modify calc to read the text values
                Calc();
                // Call NotifyPropertyChanged when the source property 
                // is updated.
                NotifyPropertyChanged(\"LensNeeded\");
            } 
        }

        public void Calc()
        {
            double WidthBased = 2.95 * (DistanceBox / WidthBox);
            double LengthBased = 3.98 * (DistanceBox / LengthBox);

            if (WidthBased < LengthBased)
            {
                LensNeeded = Math.Round(WidthBased,2);
            }else{
                LensNeeded = Math.Round(LengthBased,2);
            }
        }

        // NotifyPropertyChanged will raise the PropertyChanged event,// passing the source property that is being updated.
        public void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this,new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
**错误我现在正在获取double函数中的get {}上的StackOverflowException。有任何想法吗?     

解决方法

        抛出异常是因为该行
Text=\"{x:Static c:Variables.DistanceBox}\"
实际上是这样的
textBox.Text = Variables.DistanceBox;
这不会在C#中编译。在XAML中,它引发异常。相反,您应该从字段中创建属性:
public double DistanceBox { get; set; }
并通过添加将
Variables
设置为窗口的
DataContext
DataContext = new Variables();
到窗口的构造函数(或
Loaded
事件的处理函数)。 然后,您在XAML中使用绑定(该绑定使用转换器在ѭ11中产生ѭ10):
Text=\"{Binding DistanceBox}\"
要在值更改时调用
Calc()
,可以将属性更改为
private double m_distanceBox;
public double DistanceBox
{
    get { return m_distanceBox; }
    set
    {
        m_distanceBox = value;
        Calc();
    }
}
为确保在文本框中反映出
Variables
中的更改,您应实现
INotifyPropertyChanged
界面。 编辑:#17ѭ的C#代码:
public partial class MainWindow
{
    public MainWindw()
    {
        InitializeComponent();
        DataContext = new Variables();
    }
}
    ,        您要设定文字吗?在wpf中,您需要使用设置直接文本属性的insert方法。     ,        您在设置文本值时犯了错误:
YourTextBox.Text=YourValue;
在您的情况下:
LensNeeded.Text = WidthBased.ToString();
    ,        您应该为文本框使用数据绑定。 修改您的Variables类以将这4个值作为字符串属性公开(您不能将数据绑定到字段,而只能绑定到属性):
public class Variables
{
    // code as in your example
    public string LensValueNeeded 
    { 
      get { return LensNeeded.ToString(); }
      set { Calc(); }  // modify calc to read the text values
    }

    /// same for the other 3 values
}
当数据绑定设置为双向时,请确保修改Calc方法以从TextBox中读取当前值。您将需要使用double.Parse()方法将字符串值转换回double值: double d = double.Parse(stringValue); 将网格的DataContext设置为Variables类的实例 将您的TextBox的文本绑定到string属性:
Text = {Binding LensNeededValue}
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-