0

I have a control: DailyHours. That has a collection of custom TimeEdit controls I created. Each control is supposed to bind to the DailyHours view-model class. Instead it tries to find the values I bind to in the TimeEdit control.

An example of a TimeEdit control binding:

<bc:TimeEdit Time="{Binding CurrentOperatingHours.MondayClose}" ></bc:TimeEdit>

The TimeEdit control has its own internal values for hour and minute that are bound to Hour and Minute properties. For this reason the DataContext for the TimeEdit control is itself.

public TimeEdit()
{
  InitializeComponent();
  this.DataContext = this;
}

However this causes the DailyHours control to incorrectly bind the time value. It looks for the CurrentOperatingHours property in the TimeEdit control instead of its own view-model.

How do I get my TimeEdit control to bind correctly with internal values without disturbing binding on its parent container?

Tjaart
  • 3,912
  • 2
  • 37
  • 61

2 Answers2

5

you can go two ways: remove this.Datacontext = this; from your usercontrol and use bindings with ElementName for Hour and Minute (good practise!) or use relativeSourceBinding in your Mainview (bad practise).

i answered a similar question here.

ps: an usercontrol should never set the datacontext to it self. this brokes datacontext inheritance and its not an expected behavior.

Community
  • 1
  • 1
blindmeis
  • 22,175
  • 7
  • 55
  • 74
0

try this

Time="{Binding DataContext.CurrentOperatingHours.MondayClose, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}"> 

I hope this will work .

akjoshi
  • 15,374
  • 13
  • 103
  • 121
yo chauhan
  • 12,079
  • 4
  • 39
  • 58
  • this would work when you add DataContext to the Path: {Binding DataContext.CurrentOperatingHours.MondayClose... – blindmeis Jun 29 '12 at 11:02
  • Actually the DataContext of the control is bind to control Itself , so to find the property CurrentOperatingHours in ViewModel you need to use RelativeResource. – yo chauhan Jun 29 '12 at 11:05
  • 1
    your example bind to the Window not the usercontrol, if you try your code you will see something like this Binding.Error Property CurrentOperatingHours not found on object typeof Window – blindmeis Jun 29 '12 at 11:17