UWP x:绑定双向绑定

时间:2019-08-27 16:06:37

标签: c# data-binding uwp

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

    }

}

2 个答案:

答案 0 :(得分:0)

这就是我最终要做的。我不知道有这么多行李带双向捆绑。

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

    }

}

答案 1 :(得分:0)

任何绑定只有在收到更改通知时才会在UI中更新,可以通过两种方法进行。您需要将Foo属性设置为DependencyProperty,或者使页面实现INotifyPropertyChanged接口(在依赖项属性文档中也被调用)。