2016-12-05 49 views
1

我有一個DataGrid在我的通用Windows平臺應用程序中綁定到ObservableCollection如何調試UWP xaml綁定?

加載頁面時,datagrid未顯示。我在同一個頁面中有另一個數據網格,它幾乎相同,但綁定到另一個集合幾乎與第一個集合相同(它具有綁定問題)。

有什麼方法可以調試XAML文件嗎?

示例代碼:

<GridView Name="HourGridView" Grid.Row="4" 
      ItemsSource="{x:Bind ForeCastsByDates}" 
      Foreground="Chartreuse" > 

    <GridView.ItemTemplate> 
     <DataTemplate x:DataType="data:ForeCast"> 
         ....... 
     </DataTemplate> 
    </GridView.ItemTemplate> 

</GridView> 

未綁定的集合:

private ObservableCollection<ForeCast> ForeCastsByDates; 

是綁定以及收集:

private ObservableCollection<ForeCast> ForeCasts; 

的ForeCastsByDates是預測的一部分:

ForeCastsByDates = new ObservableCollection<ForeCast>(ForeCasts.GroupBy(x => x.Date).Select(x => x.First())); 
+0

分享示例代碼 –

+0

@VinothRajendran編輯我的帖子,帶有示例代碼 – axcelenator

+0

'ForeCastsByDates'通知了屬性(而不是項目)上的更改嗎?否則,在ForeCastsByDates上做'set'操作發出通知,或者在ctor中設置集合一次,並使用'.Clear'和'.Add'作爲將來的適配。 –

回答

0

如果我沒有錯,似乎你實際上試圖綁定到類字段而不是屬性

數據綁定需要屬性才能正常工作。爲了達到這個目的,你必須創建一個private支持字段和一個public屬性,然後可以通過數據綁定來訪問該屬性。

private ObservableCollection<ForeCast> _foreCastsByDates; 
public ObservableCollection<ForeCast> ForeCastsByDates 
{ 
    get 
    { 
     return _foreCastsByDates; 
    } 
    set 
    { 
     _foreCastsByDates = value; 
     //notify about changes 
     OnPropertyChanged(); 
    } 
} 

你可能已經注意到了屬性使用的二傳手一個OnPropertyChanged()方法。爲了實際通知有關的財產變化的用戶界面,你需要實現你的PageINotifyPropertyChanged接口:

public partial MainPage : Page, INotifyPropertyChanged 
{ 
    // your code... 

    public event PropertyChangedEventHandler PropertyChanged; 

    private void OnPropertyChanged([CallerMemberName] string propertyName = null) 
    { 
     PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));    
    } 
} 

OnPropertyChanged方法觸發PropertyChanged事件,通知屬性已經改變了聽衆。在這種情況下,我們需要通知有關ForeCastsByDates屬性的更改。使用旁邊的OnPropertyChanged方法參數中使用的CallerMemberNameAttribute,參數被自動設置爲呼叫者的名字(在這種情況下ForeCastsByDates屬性。

最後,{x:Bind}語法默認爲OneTime模式,這意味着它是僅更新一次,聽屬性更改。爲了保證所有後續更新的財產都反映,使用

{x:Bind ForecastsByDates, Mode=OneWay} 

重要的是要提的是,你必須做出更改ForecastsByDates屬性本身來通知UI (財產etter必須執行以調用OnPropertyChanged方法)。如果你只是_foreCastsByDates = something,該字段將會改變,但用戶界面不會知道它,並且變化不會被反映出來。

+0

不,x:綁定可以綁定到字段。當你以另一種方式安排RaisePropertyChanged時將會更新。顯然,這不是一種好的風格。 –

+0

酷!不知道:-O –