从后面的代码更改ItemsControl内容

时间:2015-03-16 14:45:56

标签: c# wpf

我有wpf控件TimeLineControl,代码为:

...
<ItemsControl ItemsSource="{Binding TimeLineItems}" >
   <ItemsControl.ItemTemplate>
        <DataTemplate>
             <colorLine:TimeLineItem />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
    <ItemsControl.ItemsPanel>
         <ItemsPanelTemplate>
              <StackPanel Orientation="Horizontal"/>
         </ItemsPanelTemplate>
     </ItemsControl.ItemsPanel>
</ItemsControl>
...

ColorLine是我的命名空间,TimeLineItem是我的UserControl。目前,我将ItemsSource绑定到我的TimeLineViewModelTimeLineControl的视图模型):

        ...
        private ObservableCollection<TimeLineItemViewModel> _timeLineItems;
        public ObservableCollection<TimeLineItemViewModel> TimeLineItems
        {
            get { return _timeLineItems; }
            private set
            {
                if (_timeLineItems == value) return;
                _timeLineItems = value;
                OnPropertyChanged(() => TimeLineItems);
            }
        }
        ...

我用它来更改TimeLineItems dynamicaly中的ItemsControl的数量。

但我想摆脱这2个减少的ViewModels(TimeLineViewModelTimeLineItemViewModel),实际上我只用它来控制1个值:TimeLineItems的数量 - 我知道这种逻辑将在未来持续存在并且不会改变。

所以我希望我的TimeLineControl没有ViewModel,但在代码后面使用自定义DependencyProperty(我猜),它将具有类型int。让我们称之为AmountOfSectionsProperty。当AmountOfSectionsProperty发生变化时,它会将TimeLineItemsItemsControl的数量更改为其值。

我实现了这样的属性:

 public readonly static DependencyProperty AmountOfSectionsProperty = DependencyProperty.Register("AmountOfSections",
            typeof(int),
            typeof(TimeLineControl),
            new FrameworkPropertyMetadata(1, FrameworkPropertyMetadataOptions.AffectsParentMeasure, AmountOfSectionsChangedCallback, CoerceAmountOfSectionsCallback));

        private static object CoerceAmountOfSectionsCallback(DependencyObject dependencyObject, object baseValue)
        {
            var current = (int)baseValue;
            if (current < 1) current = 1;
            if (current > 24) current = 24;
            return current;
        }

        private static void AmountOfSectionsChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
        {
            throw new NotImplementedException();
        }

        public int AmountOfSections 
        {
            get { return (int)GetValue(AmountOfSectionsProperty); }
            set { SetValue(AmountOfSectionsProperty, value); }
        }

它应该在1..24范围内。但我有点坚持实际绑定 - 如何看待我的回调方法,改变ItemsControl项的数量?

0 个答案:

没有答案