I builded a RibbonGroupBox like this in a C# file:
public class TextControl : RibbonGroupBox
{
public TextControl()
{
const double widthOfComboBoxes = 150;
Binding fontsBinding = new Binding();
fontsBinding.Source = (TextControlVM)DataContext;
fontsBinding.Path = new System.Windows.PropertyPath("Fonts");
fontsBinding.Mode = BindingMode.TwoWay;
Binding fontSizeBinding = new Binding();
fontSizeBinding.Source = (TextControlVM)DataContext;
fontSizeBinding.Path = new System.Windows.PropertyPath("FontSize");
fontSizeBinding.Mode = BindingMode.TwoWay;
/* Combobox for the fonts (Arial, etc.) */
Fluent.ComboBox fontCombo = new Fluent.ComboBox();
fontCombo.SetBinding(Fluent.ComboBox.ItemsSourceProperty, fontsBinding);
fontCombo.SelectedItem = ((TextControlVM)DataContext).DefaultFont;
fontCombo.Width = widthOfComboBoxes;
this.AddChild(fontCombo);
/* Combobox for the fontsizes */
Fluent.ComboBox fontSizeCombo = new Fluent.ComboBox();
fontSizeCombo.SetBinding(Fluent.ComboBox.ItemsSourceProperty, fontSizeBinding);
fontSizeCombo.SelectedItem = ((TextControlVM)DataContext).DefaultFontSize;
fontSizeCombo.Width = widthOfComboBoxes;
this.AddChild(fontSizeCombo);
}
}
I furthermore have a viewmodel (TextControlVM) that contains Properties for Fonts, FontSize, DefaultFont and DefaultFontSize.
When I now use this in another module like this, the DataContext in the above example is null:
<Fluent:RibbonTabItem Header="Export">
<TextControl DataContext="{Binding DataContext.TextControl}"/>
</Fluent:RibbonTabItem>
When I build the RibbonGroupBox with XAML code everything works fine, so I want to do what XAML automatically does. How can I do that?
Background: I want to use the RibbonGroupBox in several modules. That is why I build it with C#-Code, so that I can access it dynamically. The DataContext will change dependend on the call.
The
DataContextis implied in a binding automatically, so you are essentially binding toRibbonTabItem.DataContext.DataContext.TextControl, which doesn’t existTo bind to
RibbonTabItem.DataContext.TextControl, simply leave the extraDataContextout of the binding