首页 > 解决方案 > UWP x:bind 双向绑定

问题描述

目标:使用双向绑定创建两个绑定到同一个对象的文本框,这样如果我更新其中一个文本,我会看到另一个自动显示我正在输入的文本,反之亦然。我还希望看到相同的文本出现在文本块中(只读,单向绑定)。我需要使用 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>

C#

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

    }

}

标签: c#data-bindinguwp

解决方案


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

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>

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"));
            }
        }

    }

}

推荐阅读