c# - 如何调试 UWP xaml 绑定(bind)?

标签 c# xaml debugging uwp

在我的通用 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/

相关文章:

c# - XmlSerializer 缓存工厂

silverlight - 自定义 UserControl 属性未通过 Silverlight 4 中的 XAML DataBinding 设置

wpf - 在 Setter.Value 结构中设置事件处理程序

eclipse - 是否可以将调试 session 附加到Eclipse CDT中正在运行的程序

c# - 关于WCF服务的简单查询

c# - 当我尝试加入 2 个数据表时,对象引用未设置为对象的实例

c# - 根据数据库选择突出显示/禁用ajax日历控件中的特定日期

c# - Windows Phone 8.1 页面导航

Java - 奇怪的目录问题?

c++ - 尽管有错误,glDebugMessageCallback 不会被调用