c# - 防止重新排序第一列

标签 c# wpf listview gridview

我有一个 ListView ,其中包含一个带有网格列的 GridView ,我想重新排序除第一列之外的所有列。我怎样才能做到这一点?我也想保存新列的位置。

我的 ListView 代码是:

<Style x:Key="myListViewStyle" TargetType="{x:Type ListView}"  x:Shared="False">
        <Setter Property="BorderBrush" Value="RoyalBlue" />
        <Setter Property="Foreground"  Value="Teal" />
        <Setter Property="FontSize" Value="14" />
        <Setter Property="Margin" Value="20, 60, 20, 50" />
        <Setter Property="BorderThickness" Value="4, 4, 4, 4" />
        <Setter Property="ListView.View">
            <Setter.Value>
                <GridView AllowsColumnReorder="True" >
                    <GridView.Columns>
                        <GridViewColumn Header="A/A" Width="30" DisplayMemberBinding="{Binding AA}"></GridViewColumn>
                        <GridViewColumn Header="Price" Width="350" DisplayMemberBinding="{Binding Price}" >
                        </GridViewColumn>
                        <GridViewColumn Header="Shop" Width="200" DisplayMemberBinding="{Binding Shop}" >
                        </GridViewColumn>
                    </GridView.Columns>
                </GridView>
            </Setter.Value>
        </Setter>
    </Style>

我也用这样的代码创建 ListView :

 ListView l1 = new ListView();
 l1.Style = Resources["myListViewStyle"] as Style;

最佳答案

如果您只想保留第一列,请尝试以下操作:

XAML:

<GridViewColumnHeader x:Name="FirstColumn" MouseMove="PreventDrag">

代码隐藏:

public MyWindow()
{
    InitializeComponent();
    (MyListview.View as GridView).Columns.CollectionChanged += ColumnsReordered;
}

private void PreventDrag(object sender, MouseEventArgs e)
{
    if (e.LeftButton == MouseButtonState.Pressed)
        e.Handled = true;
}

private void ColumnsReordered(object sender, NotifyCollectionChangedEventArgs e)
{
    if (e.Action == NotifyCollectionChangedAction.Move)
    {
        var columns = sender as GridViewColumnCollection;
        if (columns != null)
            Dispatcher.BeginInvoke((Action)(() => columns.Move(columns.IndexOf(FirstColumn.Column), 0)));
    }
}

关于c# - 防止重新排序第一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15729301/

相关文章:

C# "must declare a body because it is not marked abstract, extern, or partial"

sql - 如何将 SQL Server 数据库分发给客户端

android - ArrayAdapter - 使用多个搜索词进行过滤

c# - 设置ListView行背景

c# - 在 C# 中为 ASP.NET 重写方法时,我应该调用基类实现吗?

c# 2 个模型在同一 View 中

c# - 如何通过事件从 UserControl 的代码后面触发 JS

c# - WPF 的 TextBox 中的 ScrollToCaret 在哪里?

wpf - 错误窗口在 MVVM WPF 中显示模式

android - 过滤 ListView 突出显示不正确的项目