在我的通用 Windows 平台应用程序中,我有一个 DataGrid
绑定(bind)到一个 ObservableCollection
。
加载页面时不显示数据网格。我在同一页面中有另一个数据网格,它几乎相同但绑定(bind)到另一个集合几乎与第一个相同(有绑定(bind)问题)。
有什么方法可以调试 XAML
文件吗?
示例代码:
<GridView Name="HourGridView" Grid.Row="4"
ItemsSource="{x:Bind ForeCastsByDates}"
Foreground="Chartreuse" >
<GridView.ItemTemplate>
<DataTemplate x:DataType="data:ForeCast">
.......
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
未绑定(bind)的集合:
private ObservableCollection<ForeCast> ForeCastsByDates;
绑定(bind)好的集合:
private ObservableCollection<ForeCast> ForeCasts;
ForeCastsByDates 是 ForeCasts 的一部分:
ForeCastsByDates = new ObservableCollection<ForeCast>( ForeCasts.GroupBy(x => x.Date).Select(x => x.First()));
最佳答案
如果我没记错的话,看来您实际上是在尝试绑定(bind)到类字段,而不是属性。
数据绑定(bind)需要属性才能正常工作。为此,您必须创建一个 private
支持字段和一个 public
属性,然后可以通过数据绑定(bind)访问它们。
private ObservableCollection<ForeCast> _foreCastsByDates;
public ObservableCollection<ForeCast> ForeCastsByDates
{
get
{
return _foreCastsByDates;
}
set
{
_foreCastsByDates = value;
//notify about changes
OnPropertyChanged();
}
}
您可能已经注意到该属性在 setter 中使用了 OnPropertyChanged()
方法。要实际通知用户界面有关属性的更改,您需要在 Page
上实现 INotifyPropertyChanged
接口(interface):
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
模式,即只更新一次,不监听属性(property)变了。为确保反射(reflect)所有以后对该属性的更新,请使用
{x:Bind ForecastsByDates, Mode=OneWay}
值得一提的是,您必须更改 ForecastsByDates
属性本身以通知 UI(必须执行属性 setter 以调用 OnPropertyChanged
方法).如果您只执行 _foreCastsByDates = something
,该字段将发生变化,但 UI 不会知道并且不会反射(reflect)该变化。
关于c# - 如何调试 UWP xaml 绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40980977/