简体   繁体   English

将 Id 添加到 ListBox 项

[英]Add an Id to ListBox item

I need to add an ID (x:Uid="identifier") to the last and first listbox item.我需要向最后一个和第一个列表框项添加一个 ID (x:Uid="identifier") My Listbox items are populated via data-source like this:我的列表框项目是通过这样的数据源填充的:

<ListBox x:Name="listbox1" Grid.Row="1" BorderThickness="0" 
     ItemsSource="{SomeBinding}">

Could it be done in xaml?可以在xaml中完成吗?

I'm not sure how you want to implement it, but here's some kinda of solution.我不确定你想如何实现它,但这里有一些解决方案。

I figured you just need IDs of first and last items in your ListBox.我认为您只需要 ListBox 中第一个和最后一个项目的 ID。 Not sure you can do it in xaml without much work and headache.不确定您是否可以在 xaml 中完成它而无需太多工作和头痛。 You already have it binded to some object.您已经将它绑定到某个对象。 Let's say:让我们说:

XAML: XAML:

<ListBox x:Name="listbox1" ItemsSource="{Binding Items}"/>

Code behind:后面的代码:

private ObservableCollection<Item> _Items;
public ObservableCollection<Item> Items
{
    get { return _Items; }
    set { _Items = value; }
}

So you could just get 'em like this:所以你可以像这样得到它们:

private void Button_Click(object sender, RoutedEventArgs e)
{
    var firstItem = Items[0];
    var lastItem = Items[Items.Count - 1];
}

Inherit from ListBox your custom class.ListBox继承您的自定义类。 Override protected method.. not quite remember which was the name... something about .GetContainerFor(...) .覆盖受保护的方法……不太记得名字是什么……关于.GetContainerFor(...)一些东西。 From there you might return new ListBoxItem() and set it up as you prefer.从那里您可能会返回new ListBoxItem()并根据您的喜好进行设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM