0

How can I pass a string into a method?

I tried

private void UpdateValueRanges( .... , ref string decimalValueRange)
{ 
    ...
    decimalValueRange = "10..20";

But I get the warning the the argument is overwritten without being used.

What I want to pass is the string that is bound to a text box control (via WPF, MVVM) and since I have multiple text box controls I want to pass the string belonging to the bound text box ... or can I only do this by passing the text box control itself?

Michel Keijzers
  • 15,025
  • 28
  • 93
  • 119

1 Answers1

1

I do not know if I understand your problem but if you want simply change control's property sending it as parameter with 'ref' maybe you should try this:

<!-- Window1.xaml -->
...
<Grid>
  <TextBox Text={Binding MySampleText} />
</Grid>
...

I made simple binding from CodeBehind, first implement

/* Window1.xaml.cs */
public partial class Window1 : Window, INotifyPropertyChanged
{
  public event PropertyChangedEventHandler PropertyChanged;
  ...
}

Next full property with OnPropertyChanged trigger and handler:

private string _mySampleText;
public string MySampleText
{
    get { return _mySampleText; }
    set
    {
        if (value != _mySampleText)
        {
            _mySampleText = value;
            OnPropertyChanged("MySampleText");
        }
    }
}

...

protected void OnPropertyChanged(string passedValue)
{
    var handler = PropertyChanged;
    if (handler != null)
        handler(this, new PropertyChangedEventArgs(passedValue));
}

Finally constructor with method call:

public Window1()
{
    InitializeComponent();
    DataContext = this;

    UpdateValueRanges(ref _mySampleText);
}

private void UpdateValueRanges(ref string decimalValueRange)
{
    decimalValueRange = "10..20";
}

If u have alert that "...the argument is overwritten without being used", use 'out' instead of 'ref' -

When to use ref vs out

public Window1()
{
    InitializeComponent();
    DataContext = this;

    UpdateValueRanges(out _mySampleText);
}

private void UpdateValueRanges(out string decimalValueRange)
{
    decimalValueRange = "10..20";
}

Here is similar problem maybe that I found - Pass by Ref Textbox.Text

Community
  • 1
  • 1
Borys Rybak
  • 100
  • 1
  • 9