在Universal Windows App风格的Xaml中,我想创建一个具有非常相似的附加属性的自定义面板,例如Canvas.Left(或Top,Right或Bottom)。所以我可以根据guide
创建一个public static readonly DependencyProperty XProperty =
DependencyProperty.RegisterAttached("X", typeof(double), typeof(Track), null);
public static double GetX(DependencyObject d)
{
return (double)d.GetValue(XProperty);
}
// SetX and property wrapper omitted for brevity here
现在我可以写
了<c:Track>
<TextBlock Text="1" c:Track.X="1"/>
<TextBlock Text="2" c:Track.X="2"/>
<TextBlock Text="3" c:Track.X="3"/>
</c:Track>
然后我可以在
中使用我附加的值public override void ArrangeOverride(Size finalSize)
{
foreach (var child in Children)
{
var x = GetX(child);
child.Arrange(CalculateArrange(x, finalSize));
}
}
到目前为止,一切都运转良好。
但是,当我们来到ItemsControl时,我可以这样做,
<ItemsControl ItemsSource="{Binding ListOfInts}">
<ItemsControl.ItemPanel>
<ItemPanelTemplate>
<Canvas/>
</ItemPanelTemplate>
</ItemsControl.ItemPanel>
<ItemsControl.ItemTemplate>
<DataTemplate x:DatatType="Int">
<TextBlock Canvas.Left="{Binding}" Text="{Binding}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
但如果我想为我自己的自定义面板做这件事,我必须这样做
<ItemsControl ItemsSource="{Binding ListOfInts}">
<ItemsControl.ItemPanel>
<ItemPanelTemplate>
<Track/> <!--Change to my panel-->
</ItemPanelTemplate>
</ItemsControl.ItemPanel>
<ItemsControl.ItemContainerStyle> <!-- need to add the attached property here -->
<Style TargetType="ContentPresenter">
<Setter Property="c:Track.X" Value="{Binding}"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate x:DatatType="Int">
<TextBlock Text="{Binding}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
因为我做不到
public override void ArrangeOverride(Size finalSize)
{
//Children are now contentPresenters
foreach (ContentPresenter child in Children)
{
var controlWithAttribute = child.????
//child.Content is the same as DataContext i.e. an Int
var x = GetX(controlWithAttribute);
child.Arrange(CalculateArrange(, finalSize));
}
}
我缺少什么想法?如何让ItemsControl与Canvas.Left一样工作?