WinRT 绑定,UI 不会更新
本文关键字:更新 UI 绑定 WinRT | 更新日期: 2023-09-27 18:36:22
我有一个加载一些数据的视图模型。加载时,依赖项属性设置为 true,稍后再次设置为 false。我经常在 WPF 中执行此操作,但对于现代应用程序,它不起作用。:(
绑定到模型的视图应显示模型是否仍在加载。它仅在加载页面时显示值,但在值更改后不会更新视图。
我写了一个小示例,该示例使用SharedProjects for Phone,Modern App和WPF。(绑定示例)
出于测试目的,它只是在真和假之间切换。
XAML
<Page
x:Class="App2.BlankPage1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App2"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid >
<TextBlock Text="{Binding Loading, Mode=OneWay}" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="30" Width="100" Height="100"/>
</Grid>
</Page>
页面的构造函数
public BlankPage1()
{
var v = new Viewmodle();
this.InitializeComponent();
this.DataContext = v;
v.Test();
}
视图模型:
public class Viewmodle : DependencyObject
{
public bool Loading
{
get { return (bool)GetValue(LoadingProperty); }
set { SetValue(LoadingProperty, value); }
}
// Using a DependencyProperty as the backing store for Loading. This enables animation, styling, binding, etc...
public static readonly DependencyProperty LoadingProperty =
DependencyProperty.Register("Loading", typeof(bool), typeof(Viewmodle), new PropertyMetadata(false));
public async void Test()
{
while (true)
{
await System.Threading.Tasks.Task.Delay(1000);
this.Loading = true;
await System.Threading.Tasks.Task.Delay(1000);
this.Loading = false;
}
}
}
您可能想要 INotifyPropertyChanged 而不是 DependencyObject。您现在绑定的方式实际上只是一个普通属性绑定,它并没有真正使用 DependencyProperty。这可以通过删除 CLR 属性并仅具有依赖项属性注册来证明。您将看到绑定在运行时失败。依赖项属性绑定似乎仅在源源自 xaml 时才有用。因此,与其按照您的方式在代码中设置视图模型,不如执行以下操作
<Grid.Resources>
<local:Viewmodle x:Name="viewModel"/>
</Grid.Resources>
<TextBlock Text="{Binding ElementName=viewModel, Path=Loading}"/>
然后,您可以在构造函数中调用 viewModel.Test() 以使用 XAML 创建的视图模型开始测试