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?