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