How to set DataContext of a single control to code the behind?
Cannot use DataContext of the Windows as it points to something else.
For a single control I would like to set the DataContext to codebehind but cannot figure it out.
Not using MVVM.
This is not working as the RelativeSource appears to the ComboBox.
<ComboBox DataContext="{Binding RelativeSource={RelativeSource Self}}" ItemsSource="{Binding Path=Chars}" SelectedItem="{Binding Path=Comma}" Width="40" PresentationTraceSources.TraceLevel="High" />
It is a Page - not a Window
This works:
<ComboBox DataContext="{Binding RelativeSource={RelativeSource AncestorType=Page}}" ItemsSource="{Binding Path=Chars}" SelectedItem="{Binding Path=Comma, Mode=TwoWay}" Width="40" PresentationTraceSources.TraceLevel="High" />
Is there a better solution?
Converting my comment to an answer :
since you aren't following MVVM, you could get away with giving your ComboBox
a Name and assigning DataContext
to it directly from your code-behind.
<ComboBox x:Name="cmBox" ... />
and in the code-behind class's ctor:
Loaded += (sender, args) => cmBox.DataContext = this;
saying ^^, there is nothing wrong with using a RelativeSource
Binding to assign DataContext
directly from xaml, It's what I'd prefer to do myself(but I do "try to" comply with MVVM in my apps).