K. Fenster
K. Fenster

Reputation: 91

Binding DataContext in XAML With DataContext Set In Code

I have the following code:

ProcessMainWindow.xaml.cs

public ProcessMainWindow(SourceTableRowInfo rowContent)
    {
        InitializeComponent();
        this.DataContext = rowContent;
    }

ProcessMainWindow.xaml

  <!--Insert Code---->
  <TabItem x:Name="postProcessTab" Header="Post-Processes">
            <local:PostProcessUserControl PostProcessItem="{Binding PostProcess, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
        </TabItem>

So RowContent has an element called PostProcess in it. I am trying to bind that element to a UserControl Dependency Property, but cannot get the binding to work. Based off what I was reading here (Using the DataContext) my understanding is that what I have should work, but I can't get it to work. So am I misunderstanding what it is saying? I have read a few other pages but still can't figure it out.

I have also tried:

<!--Insert Code---->
  <TabItem x:Name="postProcessTab" Header="Post-Processes">
            <local:PostProcessUserControl PostProcessItem="{Binding, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, Path=PreProcess}" />
        </TabItem>

If these are correct, I guess I have an error elsewhere in my code. I have yet to fully understand data binding in WPF to know if that is the case though so any help would be appreciated.

Upvotes: 0

Views: 179

Answers (1)

One thing to try is to put a trace on the Binding:

PostProcessItem="{Binding PostProcess, PresentationTraceSources.TraceLevel=High}. 

Then look for what it tells you at runtime in the Output pane in VS. This can help you identify cases where your DataContext isn't what you think it is, or your Path is misspelled -- all the simple stuff that the compiler catches in C# but can't be detected at compile time in a late-binding/duck-typed miasma like XAML.

Don't leave those traces on bindings once you're done with them; they can really slow things down. Or at least set TraceLevel=None, to save trouble if think you'll be coming back to one later.

Upvotes: 1

Related Questions