WPF中列表控件如何自动绑定序号
ItemsControl的写法
<TextBlock>
<TextBlock.Text>
<Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type ContentPresenter}}"
Path="(ItemsControl.AlternationIndex)" Converter="{StaticResource NumberConverter}" />
</TextBlock.Text>
</TextBlock>
listbox listview等带可选控件写法
<ListBox
Style="{StaticResource stateList}"
ItemsSource="{Binding StateList,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
SelectedItem="{Binding StateSelected,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
Tag="{Binding}" AlternationCount="{Binding Path=StateList.Count}"/>
在每一行的style中写上
<!-- 序号 -->
<Border Background="Transparent" BorderThickness="0" Width="20">
<TextBlock Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=TemplatedParent.(ItemsControl.AlternationIndex),Converter={StaticResource NumberConverter}}"
Foreground="#38393B" FontSize="12"></TextBlock>
</Border>
因为下标是从0开始的,序号需要从1开始,添加一个转换器
public class NumberConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null)
return 0;
return System.Convert.ToInt32(value) + 1;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}