Why is the C# variable not updated?

mauede 221 Reputation points
2022-05-02T18:00:15.21+00:00

@Hui Liu-MSFT
Thank you for all your help.
The problem I am having with the code you sent me is that if a wrong value is entered in the TextBox (DiceTol.Text) a red arrow appears beside the entered value and, as you stated, the property DiceThreshold is not updated with the wrong value. The wrong value keeps being displayed in the TextBox because the code has no way to know whether the value entered is right or wrong.
When the button "Load Matched Structures" is clicked, the content of the property DiceThreshold is used to sift out the names displayed in the rightmost column. The code uses the Dice coefficient to automatically rename the strings in the 4th column according to the gold standard string in the leftmost column. The Dice Coefficient returns an estimate of the guess goodness between 0 and 1. By entering a value between 0 and 1 in the TextBox (DiceTol.Text) the user decides to discard all the guessed strings that scored a value below the entered threshold.
When the code has to decide which strings to display in the rightmost column, it needs to know the content of DiceThreshold. You are telling me DiceThreshold is updated if and only if the entered value is between 0 and 1 so I can use it safely (I will check that).
However, when the entered value is not accepted then it has to be reset to its default value when the button "Load Matched Structures" is clicked.
How can the code that handles the clicking event know when to use the content of DiceThreshol and when to use the default value?
If I define a boolean variable inside the namespace but outside the Mainwindow class then will your data validation procedure be able to set it to True when a right value is entered and to False when a wrong value is entered? Will that boolean variable be accessible by the code inside MainWindow class?
Thank you

XAML
XAML
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
760 questions
0 comments No comments
{count} votes

Accepted answer
  1. Hui Liu-MSFT 37,946 Reputation points Microsoft Vendor
    2022-05-03T09:32:46.42+00:00

    MainWindow.xaml:

    198502-c.txt
    MainWindow.xaml.cs:

    using System;  
    using System.Collections.Generic;  
    using System.Collections.ObjectModel;  
    using System.Linq;  
    using System.Windows;  
    using System.Windows.Controls;  
    using System.Windows.Data;  
    using System.Windows.Input;  
    using System.ComponentModel;  
    using System.Globalization;  
    using System.Runtime.CompilerServices;  
    
    namespace PropertyNotifyDemo  
    {  
      public partial class MainWindow : Window, INotifyPropertyChanged  
      {  
        private double diceThreshold = 0.33;  
        public double DiceThreshold  
        {  
          get { return diceThreshold; }  
    
          set { diceThreshold = value; OnPropertyChanged("DiceThreshold"); }  
        }  
        private bool _hasError = false;  
    
        public bool HasError  
        {  
          get  
          {  
            return _hasError;  
          }  
    
          set  
          {  
            _hasError = value;  
            OnPropertyChanged("HasError");  
          }  
        }  
        const double DiceThresholdDefault = 0.33;  
        public List<T> InitList<T>(int count, T initValue)  
        {  
          return Enumerable.Repeat(initValue, count).ToList();  
        }  
        public MainWindow()  
        {  
          InitializeComponent();  
          DataContext = this;  
    
        }  
        public event PropertyChangedEventHandler PropertyChanged;  
        protected void OnPropertyChanged([CallerMemberName] string name = null)  
        {  
          PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));  
        }  
    
        private void Button_Click(object sender, RoutedEventArgs e)  
        {  
          if (HasError == true)  
          {  
            DiceThreshold= DiceThresholdDefault;  
          }  
        }  
      }  
      public enum SpecialFeatures  
      {  
        None,  
        Color,  
        Highlight  
      }  
      public class DoubleRangeRule : ValidationRule  
      {  
        public double Min { get; set; }  
        public double Max { get; set; }  
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)  
        {  
          double parameter = 0;  
          try  
          {  
            if (((string)value).Length > 0)  
            {  
              parameter = Double.Parse((String)value);  
            }  
          }  
          catch (Exception e)  
          {  
            MessageBox.Show("Illegal characters or " + e.Message, "Warning ", MessageBoxButton.OK, MessageBoxImage.Warning);  
            return new ValidationResult(false, "Illegal characters or " + e.Message);  
          }  
    
          if ((parameter < this.Min) || (parameter > this.Max))  
          {  
            MessageBox.Show("Invalid Dice Threshold. Enter a number between " + this.Min + " and " + this.Max, "Warning ", MessageBoxButton.OK, MessageBoxImage.Warning);  
            return new ValidationResult(false,  
                "Please enter value in the range: "  
                + this.Min + " - " + this.Max + ".");  
          }  
          return new ValidationResult(true, null);  
        }  
      }  
      public class PTAccess  
      {  
        static void OrThrow(bool result, dynamic source)  
        {  
          if (!result)  
          {  
            string errorMessage = source.getErrorMessage();  
            MessageBox.Show($"{errorMessage}. Abort application! ", "Error ", MessageBoxButton.OK, MessageBoxImage.Error);  
            App.Current.Shutdown();                             // TERMINATE APPLICATION  
            Application.Current.MainWindow.Close();  
          }  
        }  
      }  
    
      public class ProtocolSettingsLayout  
      {  
        public static readonly DependencyProperty MVVMHasErrorProperty = DependencyProperty.RegisterAttached("MVVMHasError",  
                                                                        typeof(bool),  
                                                                        typeof(ProtocolSettingsLayout),  
                                                                        new FrameworkPropertyMetadata(false,  
                                                                                                      FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,  
                                                                                                      null,  
                                                                                                      CoerceMVVMHasError));  
    
        public static bool GetMVVMHasError(DependencyObject d)  
        {  
          return (bool)d.GetValue(MVVMHasErrorProperty);  
        }  
    
        public static void SetMVVMHasError(DependencyObject d, bool value)  
        {  
          d.SetValue(MVVMHasErrorProperty, value);  
        }  
    
        private static object CoerceMVVMHasError(DependencyObject d, Object baseValue)  
        {  
          bool ret = (bool)baseValue;  
    
          if (BindingOperations.IsDataBound(d, MVVMHasErrorProperty))  
          {  
            if (GetHasErrorDescriptor(d) == null)  
            {  
              DependencyPropertyDescriptor desc = DependencyPropertyDescriptor.FromProperty(Validation.HasErrorProperty, d.GetType());  
              desc.AddValueChanged(d, OnHasErrorChanged);  
              SetHasErrorDescriptor(d, desc);  
              ret = System.Windows.Controls.Validation.GetHasError(d);  
            }  
          }  
          else  
          {  
            if (GetHasErrorDescriptor(d) != null)  
            {  
              DependencyPropertyDescriptor desc = GetHasErrorDescriptor(d);  
              desc.RemoveValueChanged(d, OnHasErrorChanged);  
              SetHasErrorDescriptor(d, null);  
            }  
          }  
    
          return ret;  
        }  
    
        private static readonly DependencyProperty HasErrorDescriptorProperty = DependencyProperty.RegisterAttached("HasErrorDescriptor",  
                                                                                typeof(DependencyPropertyDescriptor),  
                                                                                typeof(ProtocolSettingsLayout));  
    
        private static DependencyPropertyDescriptor GetHasErrorDescriptor(DependencyObject d)  
        {  
          var ret = d.GetValue(HasErrorDescriptorProperty);  
          return ret as DependencyPropertyDescriptor;  
        }  
    
        private static void OnHasErrorChanged(object sender, EventArgs e)  
        {  
          DependencyObject d = sender as DependencyObject;  
    
          if (d != null)  
          {  
            d.SetValue(MVVMHasErrorProperty, d.GetValue(Validation.HasErrorProperty));  
          }  
        }  
    
        private static void SetHasErrorDescriptor(DependencyObject d, DependencyPropertyDescriptor value)  
        {  
          var ret = d.GetValue(HasErrorDescriptorProperty);  
          d.SetValue(HasErrorDescriptorProperty, value);  
        }  
      }  
    
    }  
    

    The result:

    198482-6.gif


    If the response is helpful, please click "Accept Answer" and upvote it.
     Note: Please follow the steps in our [documentation][5] to enable e-mail notifications if you want to receive the related email notification for this thread. 

    [5]: https://learn.microsoft.com/en-us/answers/articles/67444/email-notifications.html


0 additional answers

Sort by: Most helpful