I have a UserControl with a TextBox and I want to expose TextBox.Text
property. We must take into consideration that TextBox.Text
and the DependencyProperty binded to it, are not always the same values. And I explain it a little bit deeper:
<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>
And this code-behind:
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
});
}
In this simple example, if we run the application and we type "Hello" in myTextBox
and we do not lose the focus , we would have that TextBox.Text
is "Hello", but BindingText
(our DependencyProperty) is still empty (until we lose the focus and the binding updates).
In other words, what I would like is to be able to bind to something like this:
public string Text
{
get => myTextBox.Text;
set => myTextBox.Text = value;
}
But I this does not work, I guess because it is not a DependencyProperty. Is it possible to create a DependencyProperty that exposes myTextBox.Text
anyway?
From my limited testing, this solution appears to be sufficient for your needs
Code behind:
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.