1

我有一个ListBox

<ListBox x:Name="HistogramListBox" Grid.Column="1" Margin="8,2,8,0"
         HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
         Template="{StaticResource HistogramListBoxControlTemplate}"
         ItemContainerStyle="{StaticResource HistogramListBoxItem}"
         ItemTemplate="{DynamicResource BucketTemplate}" />

这使用 a DataTemplate,而后者又使用 aValueConverter来确定 的高度ListBoxItem

<DataTemplate x:Key="BucketTemplate">
    <StackPanel>
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="100"/>
            </Grid.RowDefinitions>
            <StackPanel HorizontalAlignment="Stretch" VerticalAlignment="Bottom">
                <Rectangle Grid.Row="0" StrokeThickness="1" VerticalAlignment="Bottom" 
                           Stroke="{Binding ElementName=MainElement, Path=BucketStroke}" 
                           Fill="{Binding ElementName=MainElement, Path=BucketFill}" >
                    <Rectangle.Height>
                        <MultiBinding Converter="{StaticResource HistogramValueToPercentageConverter}">
                            <Binding Mode="OneWay" Path="ItemCount" />
                            <Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type local:Histogram}}" />
                        </MultiBinding>
                    </Rectangle.Height>
                </Rectangle>
            </StackPanel>
        </Grid>
    </StackPanel>
</DataTemplate>

ListBox ItemsSource一个int[].

当我执行代码时,它说在 Int32 上找不到“ItemCount”。我认为它从ListBox(我显然错了)中获得了项目计数。

有人可以告诉我如何让我ValueConverter知道我在做什么。

谢谢

4

3 回答 3

1

数据模板中项的数据上下文是数据项本身,它是一个int. 如果您想获得 上的属性,则ListBox需要在当前上下文之外进行操作。您可以使用 aRelativeSource来执行此操作:

{Binding Items.Count, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}
于 2009-11-10T18:46:14.550 回答
1

假设您的第一个转换器参数是实际绘制的值,第二个是直方图对象:

<Rectangle.Height>
  <MultiBinding Converter="{StaticResource HistogramValueToPercentageConverter}">
    <Binding />
    <Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type local:Histogram}}" />
  </MultiBinding>
</Rectangle.Height>

这是因为 DataContext 本身就是整数,至少从您给出的错误消息看来是这样。

顺便说一句,您通常会使用绑定而不是代码隐藏来设置 ListBox 的 ItemsSource。这导致 UI 和代码的分离更加清晰。我注意到ItemsSource=你的示例代码中没有显示,所以我想我应该提到这一点。

于 2009-11-10T22:15:28.683 回答
0

你可以试试这个为你的绑定:

<Binding Path="Items.Count">
    <Binding.RelativeSource>
        <RelativeSource AncestorType="{x:Type ListBox}" />
    </Binding.RelativeSource>
</Binding>
于 2009-11-10T19:07:36.280 回答