Search code examples
wpfbindingdependency-propertiesstackpanelgridviewcolumn

Why this Binding doesn't work properly even it gets value from source?


I have this own class :

public class PeriodContainerPanel:StackPanel
{
    public PeriodContainerPanel()
        : base()
    {
        addCollectionsToStackPanel();
    }

    private void addCollectionsToStackPanel()
    {
        this.Children.Clear();


        if (PeriodsList!=null)
        {
            double minutes = PeriodsList.Count * (Properties.Settings.Default.EndTimeSpan - Properties.Settings.Default.StartTimeSpan).TotalMinutes;
            foreach (ObservableCollection<PeriodBase> lst in PeriodsList)
            {
                this.Children.Add(new ChartUserControl(lst) { Minutes = minutes });
            }
        }
    }

    public List<ObservableCollection<PeriodBase>> PeriodsList
    {
        get { return (List<ObservableCollection<PeriodBase>>)GetValue(PeriodsListProperty); } //do NOT modify anything in here
        set { SetValue(PeriodsListProperty, value); addCollectionsToStackPanel(); } //...or here
    }

    public static readonly DependencyProperty PeriodsListProperty =
        DependencyProperty.Register(
        "PeriodsList",  //Must be the same name as the property created above
        typeof(List<ObservableCollection<PeriodBase>>), //Must be the same type as the property created above
        typeof(PeriodContainerPanel), //Must be the same as the owner class
        new UIPropertyMetadata(
            null  //default value, must be of the same type as the property
            ));
}

And i use this DependencyProperty PeriodList in UserControl like this :

<GridViewColumn>
   <GridViewColumn.CellTemplate>
   <DataTemplate>
      <UI:PeriodContainerPanel PeriodsList="{Binding RelativeSource={RelativeSource  Mode=TemplatedParent}, Path=DataContext}" />
   </DataTemplate>
   </GridViewColumn.CellTemplate>
</GridViewColumn>

I check with Convertor is there any getting process (if there is value) yes there is value and it is correct, but its not set to PeriodsList property. What is problem ? P.S if there is any question about code, please tell , i can add


Solution

  • addCollectionsToStackPanel() will not be called when binding occurs. The binding engine uses SetValue directly and that is why you should never do logic like that in the property. (Thats why it says "do NOT modify anything" in the auto generated comment)

    Use a PropertyChangedCallback for this scenario: http://msdn.microsoft.com/en-us/library/ms745795.aspx