Đây là giải pháp hack. Chúng tôi có thể sử dụng Chuyển đổi giá trị với DataBinding. Vì vậy, bước đầu tiên là tuyên bố ValueConvertor của chúng tôi:
public class ListItemToPositionConverter : IValueConverter
{
#region Implementation of IValueConverter
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var item = value as ListBoxItem;
if (item != null)
{
var lb = FindAncestor<ListBox>(item);
if (lb != null)
{
var index = lb.Items.IndexOf(item.Content);
return index;
}
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
Khai báo bất cứ nơi nào bạn muốn phương pháp tĩnh này để có được ListBox mẹ:
public static T FindAncestor<T>(DependencyObject from) where T : class
{
if (from == null)
return null;
var candidate = from as T;
return candidate ?? FindAncestor<T>(VisualTreeHelper.GetParent(from));
}
Sau đó, trong ListBox.Resources tuyên bố chuyển đổi của chúng tôi như sau:
<ListBox.Resources>
<YourNamespace:ListItemToPositionConverter x:Key="listItemToPositionConverter"/>
</ListBox.Resources>
Và cuối cùng - DataTemplate:
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}, Converter={StaticResource listItemToPositionConverter}}"/>
<Label Content="{Binding Path=DisplayName}"></Label>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
Lưu ý: trong ví dụ này các mục sẽ được tính bắt đầu bằng 0 (không), bạn có thể thay đổi nó trong phương pháp chuyển đổi bằng cách thêm 1 vào kết quả.
Hope this helps ...
Nguồn
2010-08-31 09:46:28