Weird behavior with re-usable control and DependencyProperty

I’m trying to make a small POC of a re-usable control but i’m experiencing weird behavior that I can’t for the love of god figure out why.

So I’m hoping anyone here can shed some light onto this.

I’m trying to make a re-usable numeric input, with +/- buttons and configurable min/max values.
If the min/max is set and the user enters a value that is greater or smaller, I need the control to update the bound property to either the min or max allowed value.

It all works fine when manually inputting the value, but it doesn’t work whenever the bound property is being set through code (e.g. on button click in the main viewmodel)

This the my output i’m gettin when manually filling out a value that’s too large:

Setting BindThis to 105
BindThis set to 105
UC OnPropertyChanged: 25 -> 105
UC forcing min/max value: 100)
Setting BindThis to 100
BindThis set to 100
UC OnPropertyChanged: 105 -> 100

And this is what I get when I set BindThis to a value on button click:

Setting BindThis to 1000,2345678
UC OnPropertyChanged: 100 -> 1000,2345678
UC forcing min/max value: 100)
UC OnPropertyChanged: 1000,2345678 -> 100
BindThis set to 1000,2345678

Notice how the usercontrol’s DependencyProperty stuff is being called while the property on the viewmodel is being set vs it all being done after the viewmodel’s property been set when manually filling out the value.

Note that i’m using CommunityToolkit.Mvvm and the app is running under .NET 8:
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.3.2" />
Although I doubt that this has any effect on what I’m experiencing.

Given the following UserControl:

<UserControl x:Class="WpfApp1.UserControl1"
             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" 
             xmlns:local="clr-namespace:WpfApp1"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800"
             x:Name="MyControl">
    <StackPanel Orientation="Horizontal" DataContext="{Binding ElementName=MyControl}">
        <Button Command="{Binding Decrease}" Content="-" />
        <TextBox Width="300" Text="{Binding Value}" />
        <Button Command="{Binding Increase}" Content="+" />
    </StackPanel>
</UserControl>
namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for UserControl1.xaml
    /// </summary>
    public partial class UserControl1 : UserControl
    {
        public UserControl1()
        {
            _increaseCommand = new RelayCommand(OnIncrease, CanIncrease);
            _decreaseCommand = new RelayCommand(OnDecrease, CanDecrease);

            InitializeComponent(); 
            
        }

        public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
            nameof(Value), typeof(double?), typeof(UserControl1), 
            new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, ValueProperty_OnPropertyChanged));

        // /questions/7267840/dependency-property-updating-the-source
        private static void ValueProperty_OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            Debug.WriteLine($"UC OnPropertyChanged: {e.OldValue} -> {e.NewValue}");
            UserControl1 instance = (UserControl1)d;
            double? newValue = (double?)e.NewValue;
            double? result = newValue;
            
            if(newValue != null)
            {
                if(newValue < instance.Min)
                {
                    result = instance.Min;
                }
                else if(newValue > instance.Max)
                {
                    result = instance.Max;
                }
            }

            if(newValue != result)
            {
                Debug.WriteLine($"UC forcing min/max value: {result})");
                d.SetCurrentValue(ValueProperty, result);
            }

            instance.Increase.NotifyCanExecuteChanged();
            instance.Decrease.NotifyCanExecuteChanged();
        }

        public double? Value
        {
            get => (double?)GetValue(ValueProperty);
            set => SetValue(ValueProperty, value);
        }

        public double Min { get; set; }
        public double Max { get; set; }

        private RelayCommand _increaseCommand;
        public RelayCommand Increase => _increaseCommand;
        
        private RelayCommand _decreaseCommand;
        public RelayCommand Decrease => _decreaseCommand;

        private bool CanDecrease() => Value - 1 >= Min;
        private void OnDecrease() => Value -= 1;

        private bool CanIncrease() => Value + 1 <= Max;
        private void OnIncrease() => Value += 1;
    }
}

Which is being used as such:

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <StackPanel>
        <Label Content="{Binding BindThis}" />
        <local:UserControl1 Value="{Binding BindThis, Mode=TwoWay}" Min="-100" Max="100" />
        <Button Command="{Binding ButtonClick}" Content="Over max" />
        <Button Command="{Binding ButtonMinClick}" Content="Below min" />
    </StackPanel>
</Window>
namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            DataContext = new MainWindowViewModel();
        }
    }

    public class MainWindowViewModel : ObservableObject
    {
        private double? _value;
        public double? BindThis
        {
            get => _value;
            set
            {
                Debug.WriteLine($"Setting BindThis to {value}");
                SetProperty(ref _value, value);
                Debug.WriteLine($"BindThis set to {_value}");
            }
        }
        private void OnButtonMinClick() => BindThis = -1000.12345;

        private void OnButtonClick() => BindThis = 1000.2345678;

        private RelayCommand _btnClick;
        public ICommand ButtonClick => _btnClick;

        private RelayCommand _btnMinClick;
        public ICommand ButtonMinClick => _btnMinClick;

        public MainWindowViewModel()
        {
            _btnClick = new RelayCommand(OnButtonClick);
            _btnMinClick = new RelayCommand(OnButtonMinClick);
        }
    }
}

Update 1:
As suggested in the comments, I should be using the CoarceValueCallback and don’t use SetCurrentValue in the OnPropertyChanged.
However, this results in the same behavior all over the line. The wrong value is being stored in the property on the view model, while the limited value is shown in the textbox.

These are the changes:

 public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
     nameof(Value), typeof(double?), typeof(UserControl1), 
     new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, ValueProperty_OnPropertyChanged, ValueProperty_OnCoarceValue));

 private static object ValueProperty_OnCoarceValue(DependencyObject d, object baseValue)
 {
     UserControl1 instance = (UserControl1)d;
     double? newValue = (double?)baseValue;
     double? result = newValue;

     if (newValue != null)
     {
         if (newValue < instance.Min)
         {
             result = instance.Min;
         }
         else if (newValue > instance.Max)
         {
             result = instance.Max;
         }
     }

     return result;
 }

 // /questions/7267840/dependency-property-updating-the-source
 // https://blog.scottlogic.com/2012/02/06/a-simple-pattern-for-creating-re-useable-usercontrols-in-wpf-silverlight.html
 private static void ValueProperty_OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
 {
     //Debug.WriteLine($"UC OnPropertyChanged: {e.OldValue} -> {e.NewValue}");
     UserControl1 instance = (UserControl1)d;
     //double? newValue = (double?)e.NewValue;
     //double? result = newValue;
    
     //if(newValue != null)
     //{
     //    if(newValue < instance.Min)
     //    {
     //        result = instance.Min;
     //    }
     //    else if(newValue > instance.Max)
     //    {
     //        result = instance.Max;
     //    }
     //}

     //if(newValue != result)
     //{
     //    Debug.WriteLine($"UC forcing min/max value: {result})");
     //    d.Dispatcher.BeginInvoke(() => d.SetCurrentValue(ValueProperty, result));
     //}

     instance.Increase.NotifyCanExecuteChanged();
     instance.Decrease.NotifyCanExecuteChanged();
 }

12

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật