绑定 x:加载,更新绑定值不会加载控件 (UWP)



我有一个网格元素,其中x:Load属性绑定到页面中的变量:

Page.xaml

<Page>
...
<Grid x:Name="grd" x:Load="{x:Bind LoadGrid, Mode=OneWay}">

Page.xaml.cs

public sealed partial class Page : Page
...
bool LoadGrid;

OnNavigatedTo事件处理程序收到传递的参数后,我相应地设置了LoadGrid的值:

request = (Request) e.Parameter;
if (request == null)
LoadGrid = false;
else {
LoadGrid = true;
InitializeComponent(); // Tried adding this to refresh the controls.
grd.Loaded += grd_Loaded;
}

当执行行grd.Loaded += grd_Loaded;时,会抛出一个 ArgumentException:

An exception of type 'System.ArgumentException' occurred ...
Delegate to an instance method cannot have null 'this'.

我检查并且grd的值null,即使x:Load属性为 true,绑定模式为 OneWay(控件"检查"绑定值中的更新(。

编辑

尝试 1

调用this.InitializeComponent()以重新初始化控件。

@touseefbsb建议的尝试2

使用 MVVM 方法创建用于更新属性值的事件。

尝试 3

设置负载值后尝试.FindName("grd"),不起作用。

与以前的 XAML 平台不同,在加载可视化树之前调用 OnNavigated 方法。

因此,您可以在页面的已加载事件处理程序中注册网格的已加载事件,如下所示:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
var request = e.Parameter;
if (request == null)
LoadGrid = false;
else
{
LoadGrid = true;
InitializeComponent();
this.Loaded += BlankPage1_Loaded;
}
}
private void BlankPage1_Loaded(object sender, RoutedEventArgs e)
{
grd.Loaded += Grd_Loaded;
}
private void Grd_Loaded(object sender, RoutedEventArgs e)
{
Debug.WriteLine("Grd loaded.");
}

OneWay绑定还要求该属性使用INotifyPropertyChanged接口。

首先,你的LoadGrid应该是一个属性,而不仅仅是一个字段,如下所示。

public bool LoadGrid {get; set;}

之后,您需要实现INotifyPropertyChanged,最好与ViewModel(MVVM pattren(一起使用。

使用实现创建一个ViewModel类。

public class PageViewModel : INotifyPropertyChanged
{
private bool loadGrid;
public event PropertyChangedEventHandler PropertyChanged = delegate { };

public bool LoadGrid
{
get { return this.loadGrid; }
set
{
this.loadGrid = value;
this.OnPropertyChanged();
}
}
public void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
// Raise the PropertyChanged event, passing the name of the property whose value has changed.
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}

之后,在您的页面中创建一个类型为PageViewModel的属性,例如:

public PageViewModelvm {get; set;} = new PageViewModel((;

然后在 OnNavigatedTo(( 方法中,您可以根据需要设置属性。 并且您不需要再次调用 InitializeComponent 来刷新任何内容。

if (request == null)
vm.LoadGrid = false;
else {
vm.LoadGrid = true;
grd.Loaded += grd_Loaded;
}

您需要做的最后一个更改是 xaml 中的一些更改,只需绑定到 vm.LoadGrid 而不是 LoadGrid,如下所示:

<Grid x:Name="grd" x:Load="{x:Bind vm.LoadGrid, Mode=OneWay}">

有关数据绑定的更多详细信息:https://learn.microsoft.com/en-us/windows/uwp/data-binding/data-binding-in-depth

最新更新