c# - 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();
}
}
}
解决方案
这就是我最终必须做的。我不知道双向绑定会带来这么多行李。
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"));
}
}
}
}
推荐阅读
- javascript - MongoError:池正在排出禁止的新操作
- c++ - 如何在多个源文件中使用静态成员结构?
- django - OneToOneField 在 django python3 或 fstring 或 self 属性问题中没有“用户名”成员
- swift - 关闭 SwiftUI 模式时触发一些代码
- recursion - 局部变量在递归调用的 Lotusscript 函数中是独立的吗?
- shopify - Shopify:如何收集有关我 Shopify 商店中列出的应用程序的统计信息?
- symfony - jms 序列化程序 @Exclude 类上的条件
- stenciljs - StencilJs 设置错字
- python - 大熊猫数据框管理
- python - 如何将 numpy 对象转换为常规 python 列表?