UWP x:bind 双向绑定

Dav*_*vid 3 c# data-binding uwp

目标:创建两个文本框,通过双向绑定绑定到同一对象,这样,如果我更新其中一个文本框的文本,我会看到另一个文本框自动显示我正在输入的文本,反之亦然。我还希望看到相同的文本出现在文本块中(只读、单向绑定)。我需要使用 x:bind 语法,而不是 Binding 语法

这是我到目前为止所拥有的,但不起作用:

XAML:

<Page
x:Class="App1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

<StackPanel>
    <TextBox Text="{x:Bind Foo, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
    <TextBox Text="{x:Bind Foo, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
    <TextBlock Text="{x:Bind Foo, Mode=OneWay}"/>
</StackPanel>
Run Code Online (Sandbox Code Playgroud)

C#

namespace App1
{
    public sealed partial class MainPage : Page
    {
        public string Foo {get; set;}
        public MainPage()
        {
            this.InitializeComponent();
        }

    }

}
Run Code Online (Sandbox Code Playgroud)

Dav*_*vid 5

这就是我最终必须做的。我不知道双向绑定会带来这么多行李。

XAML:

<Page
    x:Class="App1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App1"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <StackPanel>
        <TextBox Text="{x:Bind ViewModel.Foo, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
        <TextBox Text="{x:Bind ViewModel.Foo, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
        <TextBlock Text="{x:Bind ViewModel.Foo, Mode=OneWay}"/>
    </StackPanel>

</Page>
Run Code Online (Sandbox Code Playgroud)

C#:

 namespace App1
{
    public sealed partial class MainPage : Page
    {
        public TextModel ViewModel { get; set; }

        public MainPage()
        {
            ViewModel = new TextModel();
            this.InitializeComponent();
        }
    }

    public class TextModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private string foo = "hello";
        public string Foo
        {
            get => foo;

            set
            {
                foo = value;
                PropertyChanged(this, new PropertyChangedEventArgs("Foo"));
            }
        }

    }

}
Run Code Online (Sandbox Code Playgroud)