WPF的ListView绑定CheckBox数据并显示序号

5 篇文章 0 订阅

我们想在ListView中添加CheckBox数据,并且需要添加序号。

效果

最后效果如图:
在这里插入图片描述

XAML里的代码

首先xaml里面我们添加

        <ListView x:Name="lvRules" Grid.Column="1"  AlternationCount="1000000"  SelectionChanged="lbRules_SelectionChanged" MouseDown="lbRules_MouseDown" MouseDoubleClick="lbRules_MouseDoubleClick" >
             <ListView.Resources>
                 <local:IndexConverter x:Key="IndexConverterNum"  AddValue="1"/>
             </ListView.Resources>
           
             <ListView.View>
                 <GridView x:Name="lvRuleListView" >
                     <GridViewColumn Header="执行顺序" Width="80" >
                         <GridViewColumn.CellTemplate >
                             <DataTemplate>
                                 <CheckBox IsChecked="{Binding isEnable}">
                                     <TextBlock Text="{Binding (ItemsControl.AlternationIndex) ,
RelativeSource={RelativeSource AncestorType=ListViewItem},Converter={StaticResource IndexConverterNum}}" />
                                 </CheckBox>
                             </DataTemplate>
                         </GridViewColumn.CellTemplate>
                     </GridViewColumn>
                     <GridViewColumn x:Name="gvcRuleName" Header="规则名称"  DisplayMemberBinding="{Binding ruleName}" />
                     <GridViewColumn x:Name="gvcDesc" Header="规则描述"  DisplayMemberBinding="{Binding ruleDesc}" />
                 </GridView>
             </ListView.View>
         </ListView>

我们需要添加DataTemplate在GridViewColumn 中,并且绑定数据列表listRuleDatas

我的数据结构是这样的

脚本代码

public class RuleInfoData
{
    public bool isEnable { get; set; }
    public string ruleName { get; set; }
    public string ruleDesc { get; set; }
}

在脚本中我们的业务逻辑里添加和绑定数据

listRuleDatas = new List<RuleInfoData>();
listRuleDatas.Add(new RuleInfoData { isEnable = true, ruleName = nowInfo.ruleName , ruleDesc = showtxt });
lvRules.ItemsSource = listRuleDatas;

刷新数据可以用

lvRules.Items.Refresh();

关于序号

序号我们可以设置AlternationCount=“1000000”,然后显示的时候通过Binding (ItemsControl.AlternationIndex)来显示,序号是从0开始的,我们这里需要通过Converter来改变序号。

public class IndexConverter : IValueConverter
{
    public int AddValue { get; set; }

    public object Convert(object value, Type TargetType, object parameter, System.Globalization.CultureInfo culture)
    {
        int curentvalue = (int)(value);
        curentvalue += AddValue;

        return curentvalue;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        int curentvalue = (int)(value);
        curentvalue -= AddValue;
        return curentvalue;

    }
}

函数定义好后需要添加Resources

<ListView.Resources>
                 <local:IndexConverter x:Key="IndexConverterNum"  AddValue="1"/>
</ListView.Resources>

否则会报错,找不到IndexConverterNum

最后就运行就可以看到效果了。

点击CheckBox处理

我们可能还需要点击CheckBox进行数据变动。我们可以利用CheckBox的Tag来处理。
我们可以把编号添加到CheckBox的Tag,这样我们点击Tag就知道是哪一条数据了,这样做实现起来比较简单。或者也可以直接获取((TextBlock)cbBox.Content).Text,如果仅仅是个数字的话。

<GridViewColumn.CellTemplate >
	<DataTemplate>
		<CheckBox IsChecked="{Binding isEnable}" Tag="{Binding (ItemsControl.AlternationIndex) ,
RelativeSource={RelativeSource AncestorType=ListViewItem},Converter={StaticResource IndexConverterNum}}" Click="CheckBox_Click">
			<TextBlock Text="{Binding (ItemsControl.AlternationIndex) ,
RelativeSource={RelativeSource AncestorType=ListViewItem},Converter={StaticResource IndexConverterNum}}" />
		</CheckBox>
	</DataTemplate>
</GridViewColumn.CellTemplate>

后台代码里

//点击规则开关
private void CheckBox_Click(object sender, RoutedEventArgs e)
{
    CheckBox cbBox = sender as CheckBox;
    if (cbBox != null)
    {
        //((TextBlock)cbBox.Content).Text
        int index = int.Parse(cbBox.Tag.ToString()) - 1;
        lvRules.SelectedIndex = index;
       
    }

}

ListView实现简单拖拽

首先xmsl里的Listview需要添加

AllowDrop="True" MouseMove="lvRules_MouseMove" Drop="lvRules_Drop"

首先鼠标移动事件增加

private void lvRules_MouseMove(object sender, MouseEventArgs e)
{
    if (sender is ListView listview
                 && e.LeftButton == MouseButtonState.Pressed
                 && listview.SelectedItem != null)
    {
        DragDrop.DoDragDrop(listview, listview.SelectedItem, DragDropEffects.Move);
        //tbStat.Text = "lvRules_MouseMove";
    }
}

然后是释放

private void lvRules_Drop(object sender, DragEventArgs e)
{
    
    object data = e.Data.GetData(typeof(RuleInfoData));
    if (data is RuleInfoData)
    {
    	//根据位置信息获得index
        int insert_index = GetCurrentIndex(new GetPositionDelegate(e.GetPosition));
        if (insert_index == -1)
            return;
        //这里就可以处理插入了。
    }
}
private int GetCurrentIndex(GetPositionDelegate getPosition)
{
    int index = -1;
    if (lvRules.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated)
        return index;
    for (int i = 0; i < lvRules.Items.Count; ++i)
    {
        ListViewItem item = lvRules.ItemContainerGenerator.ContainerFromIndex(i) as ListViewItem;
        if (item != null && this.IsMouseOverTarget(item, getPosition))
        {
            index = i;
            break;
        }
    }
    return index;
}

delegate Point GetPositionDelegate(IInputElement element);
private bool IsMouseOverTarget(Visual target, GetPositionDelegate getPosition)
{
    Rect bounds = VisualTreeHelper.GetDescendantBounds(target);
    Point mousePos = getPosition((IInputElement)target);
    return bounds.Contains(mousePos);
}

参考文献

https://learn.microsoft.com/en-us/dotnet/desktop/wpf/controls/how-to-style-a-row-in-a-listview-that-implements-a-gridview?view=netframeworkdesktop-4.8

https://stackoverflow.com/questions/660528/how-to-display-row-numbers-in-a-listview

https://blog.csdn.net/yysyangyangyangshan/article/details/8951677

https://blog.csdn.net/porenasckx/article/details/8198157

  • 7
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
WPFListView是一个非常强大的控件,它可以用于呈现列表数据数据绑定WPF编程中的一个核心概念,通过数据绑定可以将数据和UI元素进行关联。下面是一个简单的例子,演示如何使用ListView进行数据绑定。 1. 创建一个数据模型类 首先我们需要定义一个数据模型类,用于表示每个列表项的数据。例如,我们可以定义一个Person类,包含Name和Age属性。 ```csharp public class Person { public string Name { get; set; } public int Age { get; set; } } ``` 2. 创建一个ViewModel类 接下来,我们需要创建一个ViewModel类,用于管理ListView数据源。例如,我们可以定义一个PeopleViewModel类,包含一个ObservableCollection<Person>类型的People属性,用于存储所有的Person对象。ObservableCollection是一个特殊的集合类,它可以自动通知UI元素数据源的变化。 ```csharp public class PeopleViewModel { public ObservableCollection<Person> People { get; set; } public PeopleViewModel() { People = new ObservableCollection<Person>(); People.Add(new Person { Name = "Tom", Age = 20 }); People.Add(new Person { Name = "Jerry", Age = 30 }); People.Add(new Person { Name = "Mickey", Age = 25 }); } } ``` 3. 在XAML中创建ListView控件 在XAML中创建ListView控件,并通过ItemsSource属性将其与ViewModel的People属性进行绑定。可以使用DataTemplate定义每个列表项的UI元素。 ```xml <ListView ItemsSource="{Binding People}"> <ListView.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding Name}" /> <TextBlock Text="{Binding Age}" /> </StackPanel> </DataTemplate> </ListView.ItemTemplate> </ListView> ``` 4. 在窗口代码中设置DataContext 最后,在窗口代码中设置DataContext为PeopleViewModel的实例。 ```csharp public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext = new PeopleViewModel(); } } ``` 这样,当窗口加载时,ListView就会自动显示ViewModel的People属性中的所有数据。当数据发生变化时,ListView也会自动更新。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值