i'm not really sure how to explain this... i'm going to put the code in psuedo code for easy reading
pretty much I want a label to change it's text when a bool variable of a class changes... i'm not sure what I need to use since i'm using WPF and the class can't just change the label i don't think?
do i need some sort of event? or a WPF event? thanks for any help
public MainWindow()
{
SomeClass temp = new SomeClass();
void ButtonClick(sender, EventArgs e)
{
if (temp.Authenticate)
label.Content = "AUTHENTICATED";
}
}
public SomeClass
{
bool _authenticated;
public bool Authenticate()
{
//send UDP msg
//wait for UDP msg for authentication
//return true or false accordingly
}
}
Since we are using WPF, I would use a binding and converter to accomplish this:
Then a converter that looks like:
In our XAML, we declare the converter in the resources section, then use it as the "Converter" option of the binding for "Content". In the code, we cast
value
to a bool (IsAuthenticated
is assumed to be a bool in your ViewModel), and return an appropriate string. Make sure your ViewModel implementsINotifyPropertyChanged
and thatIsAuthenticated
raises thePropertyChanged
event for this to work!Note: Since you won't be changing the
Label
via the UI, you don't need to worry aboutConvertBack
. You could set the mode toOneWay
to make sure that it never gets called though.Granted, this is very specific to this scenario. We could make a generic one:
Then a converter that looks like:
Another WPF approach other than BradledDotNet answer is to use triggers. This will be purely XAML based without converter code.
XAML:
Same rule applies as mentioned by BradledDotNet, ViewModel should be attached and "IsAuthenticated" property should raise the PropertyChanged event.
-- Add some boilerplate code as suggested by Gayot Fow --
View Code Behind:
For simplicity I will just set the DataContext of the view in code behind. For a better design you can use ViewModelLocator as explained here.
Example Model (it should really be ViewModel):
The main point here is the attached model/viewmodel has to implement INotifyPropertyChanged.
Yes, you need an event.
Consider a sample like this:
Now whenever
temp
fires theAuthenticate
event, it will change your label.