Reputation: 1527
I have a DataGrid
that is binded to an ObservableCollection
in my universal windows platform app.
The datagrid is not shown up when page is loaded. I have another datagrid in the same page that is almost the same but is binded to another collection almost the same as the first one(which has binding problems).
Is there any way to debug the XAML
file ?
Sample Code:
<GridView Name="HourGridView" Grid.Row="4"
ItemsSource="{x:Bind ForeCastsByDates}"
Foreground="Chartreuse" >
<GridView.ItemTemplate>
<DataTemplate x:DataType="data:ForeCast">
.......
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
The collection which is not binded:
private ObservableCollection<ForeCast> ForeCastsByDates;
The collection that binded well:
private ObservableCollection<ForeCast> ForeCasts;
The ForeCastsByDates is a part of ForeCasts:
ForeCastsByDates = new ObservableCollection<ForeCast>( ForeCasts.GroupBy(x => x.Date).Select(x => x.First()));
Upvotes: 2
Views: 1487
Reputation: 39082
If I am not wrong, it seems that you are actually trying to bind to a class field not a property.
Data binding requires properties to work properly. To achieve that, you will have to make a private
backing field and a public
property that can then be accessed with data binding.
private ObservableCollection<ForeCast> _foreCastsByDates;
public ObservableCollection<ForeCast> ForeCastsByDates
{
get
{
return _foreCastsByDates;
}
set
{
_foreCastsByDates = value;
//notify about changes
OnPropertyChanged();
}
}
You may have noticed the property uses a OnPropertyChanged()
method in the setter. To actually notify the user interface about changes of the property, you need to implement the INotifyPropertyChanged
interface on your Page
:
public partial MainPage : Page, INotifyPropertyChanged
{
// your code...
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
The OnPropertyChanged
method fires the PropertyChanged
event which notifies the listeners that a property has changed. In this case we need to notify about the changes to the ForeCastsByDates
property. Using the CallerMemberNameAttribute
used next to the OnPropertyChanged
method parameter, the parameter is automatically set to the name of the caller (in this case the ForeCastsByDates
property.
Finally, the {x:Bind}
syntax defaults to OneTime
mode, which means it is updated only once and does not listen to property changed. To ensure all later updates to the property are reflected, use
{x:Bind ForecastsByDates, Mode=OneWay}
Important thing to mention is that you have to make changes to the ForecastsByDates
property itself to notify the UI (the property setter has to be executed to call the OnPropertyChanged
method). If you do just _foreCastsByDates = something
, the field will change, but the UI will not know about it and the change will not be reflected.
Upvotes: 1