我有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
绑定到我的TimeLineViewModel
(TimeLineControl
的视图模型):
...
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(TimeLineViewModel
和TimeLineItemViewModel
),实际上我只用它来控制1个值:TimeLineItems
的数量 - 我知道这种逻辑将在未来持续存在并且不会改变。
所以我希望我的TimeLineControl
没有ViewModel,但在代码后面使用自定义DependencyProperty
(我猜),它将具有类型int
。让我们称之为AmountOfSectionsProperty
。当AmountOfSectionsProperty
发生变化时,它会将TimeLineItems
中ItemsControl
的数量更改为其值。
我实现了这样的属性:
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
项的数量?