2016-12-05 25 views
-1

使用MVVM模式中,應用程序的UI和底層表示和業務邏輯.XAML和代碼: 的TextBlocks,圖像這樣定義:無法綁定到mvvm中的文本塊?

<Page.DataContext> 
    <ViewModel:TweetVM/> 
</Page.DataContext> 
    <Grid> 
     <Grid.RowDefinitions> 
      <RowDefinition Height="100"/> 
      <RowDefinition/> 
      <RowDefinition Height="auto"/> 
     </Grid.RowDefinitions> 
     <StackPanel Grid.Row="0" Orientation="Horizontal" > 
      <Image x:Name="Thumbnail" Source="{Binding GetAccount.ProfileImgUrl}" Width="100" Margin="8"/> 
      <StackPanel Margin="8"> 
       <TextBlock x:Name="UserName" Text="{Binding GetAccount.Name}" Foreground="#262626" VerticalAlignment="Top"/> 
       <TextBlock x:Name="AccountName" Text="{Binding GetAccount.ScreenName}" Foreground="#666666"/> 
      </StackPanel> 

     </StackPanel> 

CODE: 這裏是全碼:

public class TweetVM : INotifyPropertyChanged 
{ 


    public event PropertyChangedEventHandler PropertyChanged; 
    private Accounts getAccount; 
    public Accounts GetAccount { 
     get { return getAccount; } 
     set 
     { 
      getAccount = value; 
      PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("GetAccount")); 
     } 
    } 
    public TweetVM() 
    { 

     GetProfile(); 
    } 

    /// <summary> 
    /// 
    /// </summary> 
    public async void GetProfile() 
    { 
     try 
     { 
      GetAccount = new Accounts(); 
      var profile = await(from index in twtContext.Account 
           where index.Type == AccountType.VerifyCredentials 
           select index).SingleOrDefaultAsync(); 

      GetAccount.Name = profile.User.Name; 
      GetAccount.ProfileImgUrl = profile.User.ProfileImageUrl; 
      GetAccount.ScreenName = profile.User.ScreenNameResponse;    
     } 
     catch (Exception ex) 
     { 
      errorDialog = new ErrorDialog(ex.Message, "Error : "); 
     } 
    } 

GetAccount獲取了數據,但沒有看到綁定到textblock,...有什麼問題? 我不明白問題出在哪裏?

+0

檢查'BindingMode' – AnjumSKhan

+0

你的問題是'異步void'方法。因爲方法沒有返回'Task',所以你不能觀察結果。如果'GetProfile'方法會拋出異常 - 什麼都不會發生 - 什麼顯然在你的情況下被削弱 – Fabio

+0

沒有errors.var profile = await(來自twtContext.Account中的索引... –

回答

0

除了再評論,如果你做到這一點應該工作:

var profile = await(from index in twtContext.Account 
    where index.Type == AccountType.VerifyCredentials 
    select index).SingleOrDefaultAsync(); 

GetAccount = new Accounts() 
{ 
    Name = profile.User.Name, 
    ProfileImgUrl = profile.User.ProfileImageUrl, 
    ScreenName = profile.User.ScreenNameResponse 
} 
+0

是的,成功。 –

+0

要小心 - 如果此解決方案的工作 - 而這會工作太多,如果賬戶沒有執行INotifyPropertyChanged - 你應該檢查你的帳戶類 - 或在這裏更好的帖吧;) – blindmeis

+0

此解決方案,因爲他沒有在賬戶類執行INotifyPropertyChanged 。如果他這樣做,那麼他自己的解決方案會工作 –

0

使用史努比和檢查以下內容:

  • 視圖的DataContext的應該是TweetVM的實例
  • 賬戶類應執行INotifyPropertyChanged
  • 賬戶屬性(你綁定)必須公開

如果所有這3點都有效,它應該工作。

+0

上簡單的

+0

我從不使用這個在MVVM項目中設置DataContext的風格:)這就是爲什麼我看不到它。 – blindmeis

+0

這是合法的方式,如果這樣做 –