0

I have very basic question regarding dependency property and data-binding. I have created a simple class name TDTVm its my ViewModel class. It has one bool dependency property named IsShaftMovingUp and its initial value is 'False' I have bound this value to one text box on UI. Now I want to show real-time value of 'IsShaftMovingUp' on the screen.

Below is my VM.

public class TDTVm : DependencyObject
{
    public static DependencyProperty ShaftMovingUpProperty = 
        DependencyProperty.Register(
            "ShaftMovingUp", 
            typeof(bool),
            typeof(TDTVm),
            new PropertyMetadata(false, ShaftMovingUpChanged));

    private static void ShaftMovingUpChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        Console.WriteLine("ok");
    }

    public bool IsShaftMovingUp 
    {
        get => (bool)GetValue(TDTVm.ShaftMovingUpProperty);                
        set => SetValue(TDTVm.ShaftMovingUpProperty, value);
    }
}

Below is my xamal code.

        <Window x:Class="WpfApplication1.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">    
        <Grid>      
            <Button Content="Button" Click="Button_Click"/>
            <TextBox Text="{Binding IsShaftMovingUp,
                     UpdateSourceTrigger=PropertyChanged}" />
        </Grid>
    </Window>

and below is my code behind:

public partial class MainWindow : Window
{
    TDTVm datacontext = new TDTVm();

    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = datacontext;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        ///Even after this line 'true' value is not getting updated on UI.
        datacontext.IsShaftMovingUp = true;
    }
}

When I click on button I am setting value of 'IsShaftMovingUp' to true. But still on UI its not getting updated. ( I have achieved this using INotifyPropertyChanged but want to try same with dependency property to understand exact difference between the two )

Thanks

mithrop
  • 3,283
  • 2
  • 21
  • 40
user2243747
  • 2,767
  • 6
  • 41
  • 61

1 Answers1

2

To fix your problem, you need to change this code

DependencyProperty.Register("ShaftMovingUp",

into

DependencyProperty.Register("IsShaftMovingUp",

Check this post, if you want to know the difference between INotifyPropertyChanged and Dependency Property.

Community
  • 1
  • 1
Yuliam Chandra
  • 14,494
  • 12
  • 52
  • 67
  • That's exactly the reason to avoid those strings and go with ```DependencyProperty.Register(nameof(IsShaftMovingUp),``` instead. nameof() will give you compile errors immediatelly. – ecth Feb 16 '21 at 09:21