Get data from WPF control into a variable
I am new with WPF, I have done some work with C# and created a few small apps for my company. I am starting to dabble with this as the main developer said that he doesn't use this due to familiarity with Win Forms. I want to branch out however and know something new and something he doesn't.
Basically I am trying to assign the value of a combo box and a textbox to their own variables so I can process them within a udf.
I have this code contained in the MainWindow.Xaml.cs file
Code:
public static class OpenEnroll
{
public bool SuppADD_AmtTooMuch(ComboBox Amt, TextBox Hourly)
{
Amt = ???
}
}
Any Help would be appreciated.
Thanks,
Garrett
Re: Get data from WPF control into a variable
You've missed the mindshift required for working well with WPF. You shouldn't be thinking in terms of pulling the data from the UI. Rather, think of exposing the data in a UI-friendly way, and interaction with the UI occurs in data-binding.
I can't really tell what you're trying to achieve from your code snippet, but the general approach is to create a class that you can data-bind your UI to, so you'll need two properties and to implement INotifyPropertyChanged. Something like this:
Code:
public class EnrollViewModel : INotifyPropertyChanged
{
private string m_amt;
private string m_hourly;
public string Amt
{
get { return m_amt; }
set
{
if (m_amt != value)
{
m_amt = value;
OnPropertyChanged("Amt");
}
}
}
public string Hourly
{
get { return m_hourly; }
set
{
if (m_hourly != value)
{
m_hourly = value;
OnPropertyChanged("Hourly");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
var propertyChangedHandler = PropertyChanged;
if (propertyChangedHandler != null)
{
propertyChangedHandler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
This "view model" class (google for "MVVM" pattern) should be the data context of your UI that contains the ComboBox and TextBox. Bind those two controls to the properties exposed here, then as you change the UI, databinding will update the instance of EnrollViewModel. This you can then grab the values from as you would any other object.
Hope this gets you a bit further. :)