【发布时间】:2019-05-08 08:58:33
【问题描述】:
我是 UWP 编程的新手。我想将一个对象绑定到 UserControl(而不仅仅是对象的属性),这样当我在 MainPage 中操作 MyModel 对象时,它会在 UserControl 中更新。 我收集到 XAML 数据绑定已经从 WPF 时代发展到现在使用预编译的 x:Bind。我读过的例子似乎很复杂,混合了不同时代的技术,或者涉及幕后魔术。我想使用 x:Bind 将数据绑定归结为它的基本要素,如果可能的话,避免使用 MVVM、集合、绑定、数据上下文等。在我单击按钮时,使用户控件显示更新后的 MyProperty 所需的代码最少更改是什么?
MainPage.xaml
<Page
x:Class="MyApp.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="using:MyApp.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid>
<controls:MyUserControl MyModel="{x:Bind MyModel}"/>
<Button Click="Button_Click"/>
</Grid>
</Page>
MainPage.xaml.cs
using MyApp.Models;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace MyApp
{
public sealed partial class MainPage : Page
{
public MyModel MyModel = new MyModel();
public MainPage() { this.InitializeComponent(); }
private void Button_Click(object sender, RoutedEventArgs e)
{ MyModel.MyProperty += 1; }
}
}
MyModel.cs
namespace MyApp.Models
{
public class MyModel
{ public int MyProperty { get; set; } }
}
MyUserControl.xaml
<UserControl
x:Class="MyApp.Controls.MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<TextBlock Text="{x:Bind MyModel.MyProperty}"/>
</UserControl>
MyUserControl.xaml.cs
using MyApp.Models;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace MyApp.Controls
{
public sealed partial class MyUserControl : UserControl
{
public MyModel MyModel
{
get { return (MyModel)GetValue(MyModelProperty); }
set { SetValue(MyModelProperty, value); }
}
public static readonly DependencyProperty MyModelProperty =
DependencyProperty.Register("MyModel", typeof(MyModel), typeof(MyUserControl), new PropertyMetadata(0));
public MyUserControl()
{ this.InitializeComponent(); }
}
}
请注意,当我在 MainPage 构造函数中设置 MyModel.MyProperty 时,UserControl 会显示该值。我尝试在 MyModel 类中使用 INotifypropertyChanged 接口,PropertyChanged 事件会在按钮单击时触发,但 UserControl 不会更新。 (所以也许我的问题是如何让 MyUsercontrol 监听并响应 MyModel 中的 propertyChanged 事件?)
我的“真实”项目显然要复杂得多,所以如果可能的话,我想坚持当前的项目结构(命名空间)。
提前感谢您的时间和耐心!祝你有美好的一天:-)
【问题讨论】: