2011-07-17 45 views
0

我是sliverlight和MVVM的初學者。 我無法將使用MVVM的另一個類的textblock屬性綁定到UI類。無法使用MVVM將另一個類的textblock屬性綁定到UI類

我的代碼在這裏。 請讓我知道如何綁定下面的Authentication.cs中的textblock屬性。

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. 
    } 
} 

回答

0

你在你的Authenitcate()方法

文本框的文本指向ErrorStatus財產寫ErrorStatus = "Access Denied";,所以它隨時更新的文本框也將得到自動更新。

您需要確定的唯一一件事就是您在與TextBox綁定的相同對象上調用Authenticate()

private Authentication authentication = new Authentication(); 

public MainPage() 
{ 
    InitializeComponent(); 

    // New line here 
    this.authentication = new Authentication(); 

    this.DataContext = authentication; 
} 

void btnAuthenticate_Click(object src, EventArgs e) 
{ 
    authentication.Authenticate(); 
} 

XAML:

<TextBlock Text="{Binding Path=ErrorStatus, Mode=TwoWay}" /> 
0

您尚未創建Authentication的新實例。以下行添加到主窗口constuctor:

// Constructor 
public MainPage() 
{ 
    InitializeComponent(); 

    // New line here 
    this.authentication = new Authentication(); 

    this.DataContext = authentication; 
} 

當你調用Authenticate(),你可以指定一個新的價值ErrorStatus,它應該在TextBlock露面。

+0

我在MainPage.xaml的Button(button1_click)中調用Authentication()實例。 所以,我無法更改屬性,如果我添加this.authentication = new Authentication();. void Authenticate() { //在這裏,我寫認證代碼.... //認證碼後,我想改變textBlock屬性取決於身份驗證狀態。 //請讓我知道如何編寫代碼。 //我添加了波紋管代碼。但我無法改變財產。 ErrorStatus =「訪問被拒絕」。 } – okame100

+0

爲什麼不呢?一旦DataContext設置正確(在構造函數中,按鈕點擊代碼之前),更新viewmodel將導致綁定將值推送到'TextBlock'。 – dlev

+0

@okame您想要在構造函數中添加該行,而不是在Authenticate中。一旦該行被添加到構造函數中,您將不需要對Authenticate進行任何更改(除了向ErrorStatus分配新值) – dlev

0

這是委託指令模式(也稱爲中繼命令)進場http://kharasoft.wordpress.com/2007/10/16/the-delegating-command/使用的,而不是在你的代碼處理按鈕點擊後面的這個模式,你的視圖模型自曝一個ICommand的實例,它只是將事件路由到視圖模型上的一個方法。現在,身份驗證在視圖模型的上下文中運行,並可以直接更新屬性。

+0

Laurent Bugnion在他的mvvmlight庫中提供了一個委託命令的實現,該庫在Silverlight中工作 –

相關問題