M
M
Mozzarella2018-03-03 09:19:10
WPF
Mozzarella, 2018-03-03 09:19:10

How to set dependency property in TabControl + UserControl WPF?

The structure is as follows: there is a TabControl with such a ContentTemplate

<TabControl.ContentTemplate>
                <DataTemplate>
                    <Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch" DataContext="{Binding Path=DataContext, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
                          >
                        <uc:FormulaEditor FormulaBinding="{Binding CurrentFormula,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" 
                                      HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
                                      StandardParameters="False"/>
                    </Grid>
                </DataTemplate>
            </TabControl.ContentTemplate>

In the DataContext of the window where the TabControl is located, a ViewModel is supplied, where there is a property that changes depending on the selected tab
public Formula CurrentFormula
        {
            get => _currentFormula;
            set
            {
                _currentFormula = value;
                NotifyPropertyChanged(nameof(CurrentFormula));
            }

In UserControl
public static readonly DependencyProperty FormulaBindingProperty =
            DependencyProperty.Register(nameof(FormulaBinding), typeof(Formula), typeof(FormulaEditor),
                new PropertyMetadata(OnFormulaChanged));
public Formula FormulaBinding
        {
            get => GetValue(FormulaBindingProperty) as Formula;
            set => SetValue(FormulaBindingProperty, value);
        }
public FormulaViewModel ViewModel => DataContext as FormulaViewModel;
private static void OnStandardParametersChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var w = d as FormulaEditor;
            if (w.ViewModel != null)
                w.ViewModel.ShowStandardParameters = (bool)e.NewValue;
        }

The problem is this: all this only works when the window is initialized, with the first tab, and when the CurrentFormula changes, the binding is not updated, and the CurrentFormula of the first tab changes on all tabs

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question