1

我有一个自定义 ListBoxItem,我正在尝试以编程方式将其添加到 ListBox,并且我希望将项目的内容包装起来。

这是自定义的 ListBoxItem:

class PresetListBoxItem : ListBoxItem
{
    public uint[] preset;

    public PresetListBoxItem(uint[] preset = null, string content = "N/A")
        : base()
    {
        this.preset = preset;
        this.Content = content;
    }
}

和 XAML:

<ListBox Name="sortingBox" Margin="5,5,0,5" Width="150" MaxWidth="150" ScrollViewer.HorizontalScrollBarVisibility="Disabled" HorizontalContentAlignment="Stretch">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Border BorderBrush="Black" BorderThickness="2" CornerRadius="3" Margin="3">
                <TextBlock Text="{Binding Path=Text}" TextWrapping="WrapWithOverflow" />
            </Border>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

以及添加的代码:

PresetListBoxItem item = new PresetListBoxItem();
item.preset = new uint[] { };
item.Content = "This is a test of an extended line of text.";
sortingBox.Items.Add(item);

当我运行代码时,该项目被添加到框中,但边框根本不显示并且它不换行。

我已经在 SO 和 Google 上寻找答案,并且我使用了 ListBoxes 和 ListViews,但似乎没有任何效果。

4

1 回答 1

0

ListBoxItem只是内容和项目的容器。如果您想使用自己的ListBoxItem覆盖容器的模板而不是项目。然后,为了正确绑定,TextBlock您必须绑定到ContentPresetListBoxItem 的属性。

<ListBox.ItemContainerStyle>
    <Style TargetType="ListBoxItem">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:PresetListBoxItem">
                    <Border BorderBrush="Black" BorderThickness="2" CornerRadius="3" Margin="3">
                        <TextBlock Text="{Binding Path=Content, RelativeSource={RelativeSource AncestorType=local:PresetListBoxItem}}"
                                   TextWrapping="WrapWithOverflow" />
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ListBox.ItemContainerStyle>

但我认为这不是最好的方法。为什么你派生自ListBoxItem?如果您不这样做,您的 XAML 将立即正常。

item.Text = "This is a test of an extended line of text.";

class PresetListBoxItem
{
    public uint[] preset;
    public string Text { get; set; }

    public PresetListBoxItem(uint[] preset = null, string content = "N/A")
      : base()
    {
        this.preset = preset;
        this.Text = content;
    }
}
于 2012-05-23T02:35:36.427 回答