私はsliverlightとMVVMの初心者です。 MVVMを使用して、別のクラスのtextblockプロパティをUIクラスにバインドできません。MVVMを使用して、別のクラスのテキストブロックプロパティをUIクラスにバインドできません。
私のコードはこちらです。 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.
}
}
MainPage.xamlのButton(button1_click)のAuthentication()インスタンスを呼び出します。 this.authentication = new Authentication();を追加した場合、プロパティを変更できませんでした。 void Authenticate() { //ここでは、認証コードを書きます.... //認証コードの後に、認証ステータスに応じてtextBlockプロパティを変更したいと思います。 //コードの記述方法を教えてください。 //ベローズコードを追加しました。私は財産を変更することができませんでした。 ErrorStatus = "アクセスが拒否されました。" } – okame100
なぜですか? DataContextが適切に(コンストラクタ内で、ボタンクリックコードの前に)設定されると、ビューモデルを更新すると、バインディングによって値が 'TextBlock'にプッシュされます。 – dlev
@okameこの行は、認証者ではなくコンストラクタに追加します。コンストラクタに行が追加されたら、Authenticateを変更する必要はありません(ErrorStatusに新しい値を代入する以外) – dlev