0

I have a dependency property in a user control.

    public ComputerListView()
    {
        InitializeComponent();

        vm = new ComputerViewModel();

        this.DataContext = vm;

        DispatcherTimer time = new DispatcherTimer(TimeSpan.FromSeconds(1), DispatcherPriority.Normal,
            delegate
            {
                  SetValue(AutoCounterProperty, vm.SimpleCounter);
            },
            Dispatcher);

    }

    public int AutoCounter
    {
        get { return (int)GetValue(AutoCounterProperty); }
        set { SetValue(AutoCounterProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Counter.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty AutoCounterProperty =
        DependencyProperty.Register("AutoCounter", typeof(int), typeof(ComputerListView), new PropertyMetadata(0));
    }

<StackPanel>
    <local:ComputerListView x:Name="computerListView" AutoCounter="{Binding VMCounter, Mode=TwoWay}"/>
    <TextBox Background="Beige" Text="{Binding VMCounter, Mode=TwoWay}"/>
    <TextBlock Background="LightCyan" Text="{Binding ElementName=computerListView, Path=AutoCounter}"/>
    <Button Content="VMCounter" Click="VMCounter_Button_Click"/>
</StackPanel>

I expect that the VMCounter property will get updated as the AutoCounter will run in dependency property and the TextBox will be updated from the VMCounter property but it shows 0, never gets updated.

I have use the AutoCounter the way I have in TextBlock, then it updates fine.

I thought the major use of DP is to be able to used as target property like in first case. Why it doesn't work that way?

zar
  • 11,361
  • 14
  • 96
  • 178
  • how are you updating `vm.SimpleCounter`? – Suresh Jun 29 '20 at 05:46
  • 1
    UserControls must never explicitly set their own DataContext when they expose bindable properties. Those properties are supposed to be bound to properties of a view model object that is provided by the parent view, via value inheritance of the DataContext property. When you explicitly set the control's DataContext, you break this feature, and you have to set the Binding's RelativeSource or ElementName property to specify the source manually. – Clemens Jun 29 '20 at 06:52
  • removing setting of `Data Context` inside user control did fix the issue. – zar Jun 29 '20 at 17:02

0 Answers0