[英]WPF DependencyProperty expose a control property
我有一个带有 TextBox 的 UserControl,我想公开TextBox.Text
属性。 我们必须考虑到TextBox.Text
和绑定到它的 DependencyProperty 并不总是相同的值。 我更深入地解释一下:
<UserControl x:Class="MySolution.MyUserControl"
Name="MyControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<StackPanel>
<TextBlock>This is my label</TextBlock>
<TextBox x:Name="myTextBox" Text="{Binding ElementName=MyControl, Path=BindingText, UpdateSourceTrigger=LostFocus}"></TextBox>
</StackPanel>
</UserControl>
而这个代码隐藏:
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
namespace MySolution
{
public partial class MyUserControl : UserControl
{
public MyUserControl()
{
InitializeComponent();
}
public string BindingText
{
get { return (string)GetValue(BindingTextProperty); }
set { SetValue(BindingTextProperty, value); }
}
public static readonly DependencyProperty BindingTextProperty =
DependencyProperty.Register(nameof(BindingText), typeof(string), typeof(MyUserControl),
new FrameworkPropertyMetadata(null)
{
BindsTwoWayByDefault = true
});
}
在这个简单的示例中,如果我们运行应用程序并在myTextBox
中键入“Hello”并且我们没有失去焦点,那么TextBox.Text
将是“Hello”,但BindingText
(我们的 DependencyProperty)仍然是空的(直到我们失去焦点和绑定更新)。
换句话说,我想要的是能够绑定到这样的东西:
public string Text
{
get => myTextBox.Text;
set => myTextBox.Text = value;
}
但我这不起作用,我猜是因为它不是 DependencyProperty。 是否可以创建一个暴露myTextBox.Text
的 DependencyProperty?
从我有限的测试来看,这个解决方案似乎足以满足您的需求
后面的代码:
public partial class MyUserControl
{
public MyUserControl()
{
InitializeComponent();
}
public string Text
{
get => myTextBox.Text;
set
{
Box.Text = value;
SetValue(TextProperty, value);
}
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register(nameof(Text), typeof(string), typeof(testControl1),
new PropertyMetadata(default(string)));
}
XAML:
<StackPanel>
<TextBlock>This is my label</TextBlock>
<TextBox x:Name="myTextBox" Text="{Binding ElementName=MyControl,Path=Text, Mode=OneWay}"/>
</StackPanel>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.