Calculating textbox with two selected combobox items

拥有回忆 提交于 2019-12-12 01:38:57

问题


My problem: Id like to , after two combobox variables are selected, to divide these two and set the Textbox to the result of the calculation.

The two Comboboxes: Körpergröße & Gewicht

The textbox: BMI

First of all, the code im using ( which apparently isnt working now)

    private void fillTextBox(float value1, float value2)
   {
       BMI.Text = (value1 / value2).ToString();
   }

    private void Körpergröße_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        float a;
        float b;
        //In this way you can compare the value and if it is possible to convert into an integer. 
        if (float.TryParse(Körpergröße.SelectedItem.ToString(), out a) && float.TryParse(Gewicht.SelectedItem.ToString(), out b))
        {

            fillTextBox(a, b);
        }


    }

    private void Gewicht_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        float a;
        float b;
        //In this way you can compare the value and if it is possible to convert into an integer. 
        if (float.TryParse(Körpergröße.SelectedItem.ToString(), out a) && float.TryParse(Gewicht.SelectedItem.ToString(), out b))
        {

            fillTextBox(a, b);
        }
    }

The default values of the two comboboxes are strings.. ("Bitte auswählen")

Pictures how it looks like now. After two int values are selected, the result of the calculation should appear in the BMI Textbox, but its still blank. it looks like the ToString() Methods do not save into a, and neither into b..therefore the values cant be used in the fillTextBox method

It would be nice if someone could answer me with a code with some sidenotes, in order for me to understand..

Thanks in advance!


回答1:


Here's an example of how you would write a trivial BMI calculator in WPF. This is the way XAML is intended to be used: All of the logic is in the View Model class, BMIViewModel. The View (XAML file) wraps a UI around that logic. The codebehind file is only used if you need to provide some special logic unique to the view itself. Very often it is not used at all. Here, it's not used.

This is very different from what you may be used to and it's a steep learning curve in a lot of ways, but I've learned to like it very much. If you break up program logic into sensible chunks in various View Models, you can present those View Models in the UI in various differing ways. You get tremendous freedom and power. Once you've got a debugged and tested View Model, you can write new UI for it without touching the program logic at all.

If you study and understand this code, you will have a rudimentary but solid basis to start learning XAML. The bindings are important, and OnPropertyChanged is very important: That notification is how the view model lets the bindings know that a value has changed.

I don't like writing this much code for a beginner, but your code (which is not your code -- it's entirely copied from bad answers to previous iterations of this question), is unusable.

XAML:

<Window 
    x:Class="TestApplication.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:TestApplication"
    Title="MainWindow" Height="350" Width="525"
    >
    <Window.DataContext>
        <local:ViewModel />
    </Window.DataContext>
    <Grid>
        <StackPanel Orientation="Vertical">
            <StackPanel.Resources>
                <Style x:Key="FieldLabel" TargetType="Label">
                    <Setter Property="Width" Value="120" />
                </Style>
                <Style TargetType="ComboBox">
                    <Setter Property="Width" Value="140" />
                </Style>
                <Style TargetType="TextBox">
                    <Setter Property="Width" Value="140" />
                </Style>
            </StackPanel.Resources>
            <StackPanel Orientation="Horizontal">
                <Label Content="Height" Style="{StaticResource FieldLabel}" />
                <ComboBox 
                    ItemsSource="{Binding Heights}"
                    DisplayMemberPath="Name"
                    SelectedValuePath="Value"
                    SelectedValue="{Binding Height}"
                    />
            </StackPanel>
            <StackPanel Orientation="Horizontal">
                <Label Content="Weight" Style="{StaticResource FieldLabel}" />
                <ComboBox 
                    ItemsSource="{Binding Weights}"
                    DisplayMemberPath="Name"
                    SelectedValuePath="Value"
                    SelectedValue="{Binding Weight}"
                    />
            </StackPanel>
            <StackPanel Orientation="Horizontal">
                <Label Content="BMI" Style="{StaticResource FieldLabel}" />
                <TextBox IsReadOnly="True" Text="{Binding BMI}" />
            </StackPanel>
        </StackPanel>
    </Grid>
</Window>

C# code behind (I added no code at all here):

using System;
using System.Windows;

namespace TestApplication
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

BMIViewModel.cs:

using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace TestApplication
{
    public class BMIListItem
    {
        public BMIListItem(string name, float value)
        {
            Name = name;
            Value = value;
        }
        public BMIListItem(float value)
        {
            Name = value.ToString();
            Value = value;
        }
        public String Name { get; set; }
        public float Value { get; set; }
    }

    public class BMIViewModel : INotifyPropertyChanged
    {
        public BMIViewModel()
        {
            //  Of course you would write loops for these in real life.
            //  You should not need help with that. 
            Heights = new List<BMIListItem>
            {
                new BMIListItem("Bitte auswählen", float.NaN),
                new BMIListItem("Dummy", 0),
                new BMIListItem(150),
                new BMIListItem(151),
                new BMIListItem(152),
                //  etc. 
            };
            Weights = new List<BMIListItem>
            {
                new BMIListItem("Bitte auswählen", float.NaN),
                new BMIListItem("Dummy", 0),
                new BMIListItem(40),
                new BMIListItem(41),
                new BMIListItem(42),
                //  etc.
            };
        }

        public List<BMIListItem> Heights { get; private set; }
        public List<BMIListItem> Weights { get; private set; }

        #region BMI Property
        private float _bmi = 0;
        public float BMI
        {
            get { return _bmi; }
            set
            {
                if (value != _bmi)
                {
                    _bmi = value;
                    OnPropertyChanged("BMI");
                }
            }
        }
        #endregion BMI Property

        #region Height Property
        private float _height = float.NaN;
        public float Height
        {
            get { return _height; }
            set
            {
                if (value != _height)
                {
                    _height = value;
                    UpdateBMI();
                    OnPropertyChanged("Height");
                }
            }
        }
        #endregion Height Property

        #region Weight Property
        private float _weight = float.NaN;
        public float Weight
        {
            get { return _weight; }
            set
            {
                if (value != _weight)
                {
                    _weight = value;
                    UpdateBMI();
                    OnPropertyChanged("Weight");
                }
            }
        }
        #endregion Weight Property

        private void UpdateBMI()
        {
            if (float.IsNaN(Weight) || float.IsNaN(Height) || Height == 0)
            {
                BMI = 0;
            }
            else
            {
                BMI = Weight / Height;
            }
        }

        #region INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(String propName)
        {
            var handler = PropertyChanged;
            if (null != handler)
            {
                handler(this, new PropertyChangedEventArgs(propName));
            }
        }
        #endregion INotifyPropertyChanged
    }
}


来源:https://stackoverflow.com/questions/34230273/calculating-textbox-with-two-selected-combobox-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!