You could use the following code.
UserControl.xaml:
<Grid>
<TextBox x:Name="myTextBox" Text="{Binding SelectedDate,
RelativeSource={RelativeSource AncestorType=UserControl}}"/>
</Grid>
UserControl.xaml.cs:
using System;
using System.Windows;
using System.Windows.Controls;
namespace UserControlWorking
{
public partial class DateTimePicker2 : UserControl
{
public DateTimePicker2()
{
InitializeComponent();
}
public static readonly DependencyProperty SelectedDateProperty =
DependencyProperty.Register(nameof(SelectedDate), typeof(DateTime), typeof(DateTimePicker2),
new FrameworkPropertyMetadata(DateTime.Now, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public DateTime SelectedDate
{
get { return (DateTime)GetValue(SelectedDateProperty); }
set
{
SetValue(SelectedDateProperty, value);
}
}
}
}
MainWindow.xaml:
<Window.DataContext>
<local:DateHelper/>
</Window.DataContext>
<Grid FlowDirection="RightToLeft" >
<StackPanel>
<local:DateTimePicker2 x:Name="myControl" SelectedDate="{Binding dateTime,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Height="60" Width="300"/>
<Button Content="Add 10 Days" Click="Button_Click" Margin="10" Width="300"/>
</StackPanel>
</Grid>
MainWindow.xaml.cs:
using System;
using System.ComponentModel;
using System.Windows;
namespace UserControlWorking
{
public partial class MainWindow : Window
{
DateHelper dtContext;
public MainWindow()
{
InitializeComponent();
dtContext = new DateHelper();
DataContext=dtContext;
dtContext.dateTime = System.DateTime.Now;
dtContext.myString = "Date";
}
private void Button_Click(object sender, RoutedEventArgs e)
{
dtContext.dateTime = dtContext.dateTime.AddDays(10);
dtContext.myString = dtContext.dateTime.ToShortDateString();
}
}
public class DateHelper : INotifyPropertyChanged
{
private DateTime _dateTime;
public DateTime dateTime
{
get { return _dateTime; }
set
{
_dateTime = value;
OnPropertyChanged(nameof(dateTime));
}
}
private string _myString;
public string myString
{
get { return _myString; }
set
{
_myString = value;
OnPropertyChanged(nameof(myString));
}
}
public event PropertyChangedEventHandler PropertyChanged;
public virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
The result:
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our [documentation][5] to enable e-mail notifications if you want to receive the related email notification for this thread.
[5]: https://learn.microsoft.com/en-us/answers/articles/67444/email-notifications.html