wpf - 没有视图模型的 WPF 用户控件
问题描述
我试图在 WPF 中创建一个用户控件,它是一个简单的视图,没有视图模型。我里面有一个标签和一个文本框。
ControlTextBox.xaml:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Name="LabelColumn"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Name="LabelControl"></Label>
<TextBox Grid.Column="1"
Name="TextBox"
Width="Auto"
HorizontalAlignment="Stretch"
Height="22"></TextBox>
</Grid>
ControlTextBox.xaml.cs:
public partial class ControlTextBox : UserControl
{
public ControlTextBox ()
{
InitializeComponent();
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(ControlTextBox),
new PropertyMetadata(default(string), new PropertyChangedCallback(OnTextChanged)));
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
private static void OnTextChanged(DependencyObject sender,
DependencyPropertyChangedEventArgs args)
{
ControlTextBox controlTextBox = sender as ControlTextBox;
controlTextBox.UpdateText(args);
}
private void UpdateText(DependencyPropertyChangedEventArgs args)
{
TextBox.Text = (string)args.NewValue;
}
}
使用控件的地方:
<controls:ControlTextBox Text="{Binding PersonModel.Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"/>
但是这种方式,在我使用控件的地方,绑定是以单一方式完成的。如果绑定的属性发生更改,我可以在文本框中看到它。但是如果我在文本框中写了一些新的东西,绑定的属性不会改变。
我应该怎么做才能从 textBox 更改为绑定属性?
解决方案
RelativeSource
在 ControlTextBox.xaml 中使用绑定:
<TextBox ...
Text="{Binding Text, RelativeSource={RelativeSource AncestorType=UserControl}}" />
并删除 PropertyChangedCallback:
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register(nameof(Text), typeof(string), typeof(ControlTextBox));
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
推荐阅读
- total.js - 一次性使用 Total js 中的数据绑定和 SET 方法为所有表单元素设置值
- javascript - 在 TypeScript 中未找到存储库错误,当我通过 typeorm 连接到 MySQL 时遇到错误
- c - 关于 RISC-V 编译器?
- android - Android:导航组件不能同时使用:
和 NavigationItemSelectedListener - time - 计算从上午 12 点开始的工作时间
- c# - 优化 INSERT、DELETE、UPDATE SQL Server 表的简单方法包括具有图像数据类型的列,无需实体框架,分 3 个步骤(C#)
- java - 我们如何在 Spring Rest 控制器中解析 rpc 格式的 xml 请求?
- vb.net - 计时器案例在 y 中包含 x
- git - 如何从 Gitlab 提交历史中删除我的电子邮件?
- distributed-system - 两阶段提交是否安全