I'm a beginner of sliverlight and MVVM. I can not bind textblock property from another class to UI class using MVVM.
My code is here. Please let me know how to bind textblock property in bellow Authentication.cs.
MainPage.xaml
<TextBlock Height="30" Margin="122,218,0,0" Name="textBlock3" Text="{Binding Path=ErrorStatus, Mode=TwoWay}" VerticalAlignment="Top" HorizontalAlignment="Left" Width="86" />
MainPage.xaml.cs
private Authentication authentication;
// Constructor
public MainPage()
{
InitializeComponent();
this.DataContext = authentication;
}
ViewModelBase.cs
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
Authentication.cs
public class Authentication : ViewModelBase
{
private string _ErrorStatus;
public string ErrorStatus
{
get
{
return _ErrorStatus;
}
set
{
_ErrorStatus = value;
NotifyPropertyChanged("ErrorStatus");
}
}
void Authenticate()
{
//Here, I write authentication code....
//After the authentication code, I want to change textBlock property depend on auth status.
//Please let me know how to write code.
}
}
You haven't created a new instance of
Authentication
. Add the following line to the main window constuctor:When you call
Authenticate()
, you can just assign a new value toErrorStatus
and it should show up in theTextBlock
.You write
ErrorStatus = "Access Denied";
in yourAuthenitcate()
methodThe TextBox's Text is pointing to the
ErrorStatus
property, so anytime it updates the TextBox will also get updated automatically.The only thing you need to be sure of is that you call
Authenticate()
on the same object that the TextBox is bound to.XAML:
This is where the delegate command pattern (also called relay command) comes into play http://kharasoft.wordpress.com/2007/10/16/the-delegating-command/ using this pattern, instead of handling button click in your code behind, your viewmodel exposes an instance of ICommand that does little more than routing the events to a method on the viewmodel. Now authenticate runs in the context of your viewmodel and can update the property directly.