如何在网格中移动项目

时间:2013-02-26 16:29:01

标签: c# .net wpf xaml mvvm

我有一个WPF Grid,并希望根据用户的输入上下移动行。这是我到目前为止所尝试的(当用户决定移动元素时的示例):

RowDefinition currentRow = fieldsGrid.RowDefinitions[currentIndex];
fieldsGrid.RowDefinitions.Remove(currentRow);
fieldsGrid.RowDefinitions.Insert(currentIndex - 1, currentRow);

我做错了吗?由于UI使用这种方法保持不变。

3 个答案:

答案 0 :(得分:3)

以下是使用ItemsControl执行您想要的操作的快速示例:

视图模型

public class ListBoxViewModel
{
    private static readonly  List<string> sortList = new List<string>() { "Unsorted", "Sorted" };
    public List<string> SortList { get { return sortList; } }

    public ObservableCollection<ItemDetail> ItemDetails { get; set; }

    #region Up Command
    ICommand upCommand;
    public ICommand UpCommand
    {
        get
        {
            if (upCommand == null)
            {
                upCommand = new RelayCommand(UpExecute);
            }
            return upCommand;
        }
    }

    private void UpExecute(object param)
    {
        var id = param as ItemDetail;

        if (id != null)
        {
            var curIndex = ItemDetails.IndexOf(id);
            if (curIndex > 0)
                ItemDetails.Move(curIndex, curIndex - 1);
        }
    }
    #endregion Up Command

    #region Down Command
    ICommand downCommand;
    public ICommand DownCommand
    {
        get
        {
            if (downCommand == null)
            {
                downCommand = new RelayCommand(DownExecute);
            }
            return downCommand;
        }
    }

    private void DownExecute(object param)
    {
        var id = param as ItemDetail;
        if (id != null)
        {
            var curIndex = ItemDetails.IndexOf(id);
            if (curIndex < ItemDetails.Count-1)
                ItemDetails.Move(curIndex, curIndex + 1);
        }
    }
    #endregion Down Command

    public ListBoxViewModel()
    {
        ItemDetails = new ObservableCollection<ItemDetail>()
        {
            new ItemDetail() { IsSelected = false, ItemName = "Customer Id", SortOrder = "Unsorted" },
            new ItemDetail() { IsSelected = true, ItemName = "Customer Name", SortOrder = "Sorted" },
            new ItemDetail() { IsSelected = false, ItemName = "Customer Age", SortOrder = "Unsorted" }
        };
    }
}

ItemDetail Class(由我制作以使事情变得更容易)

public class ItemDetail
{
    public bool IsSelected { get; set; }
    public string ItemName { get; set; }
    public string SortOrder { get; set; }
}

XAML

<UserControl.Resources>     
    <DataTemplate DataType="{x:Type vm:ItemDetail}">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition SharedSizeGroup="CheckBoxGroup" />
                <ColumnDefinition SharedSizeGroup="ItemNameGroup" />
                <ColumnDefinition SharedSizeGroup="SortGroup" />
                <ColumnDefinition Width="20" />
                <ColumnDefinition SharedSizeGroup="UpArrowGroup" />
                <ColumnDefinition SharedSizeGroup="DownArrowGroup" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <CheckBox Grid.Column="0" IsChecked="{Binding IsSelected}" VerticalAlignment="Center" />
            <Label Grid.Column="1" Content="{Binding ItemName}" />
            <ComboBox Grid.Column="2" ItemsSource="{Binding DataContext.SortList, RelativeSource={RelativeSource AncestorType={x:Type views:ListBoxExample}}}" SelectedItem="{Binding SortOrder}" />
            <Button Grid.Column="4" Command="{Binding DataContext.UpCommand, RelativeSource={RelativeSource AncestorType={x:Type views:ListBoxExample}}}" CommandParameter="{Binding}">
                <Image Source="..\images\up.png" Height="10" />
            </Button>
            <Button Grid.Column="5" Command="{Binding DataContext.DownCommand, RelativeSource={RelativeSource AncestorType={x:Type views:ListBoxExample}}}" CommandParameter="{Binding}">
                <Image Source="..\images\down.png" Height="10" />
            </Button>
        </Grid>
    </DataTemplate>
</UserControl.Resources>

<Grid Grid.IsSharedSizeScope="True">
    <ItemsControl ItemsSource="{Binding ItemDetails}" />
</Grid>

最后结果:

enter image description here

按下第一项上的向下箭头后:

enter image description here

希望这有帮助。

答案 1 :(得分:3)

这将是你截图的WPF方法:

<Window x:Class="WpfApplication4.Window9"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window9" Height="300" Width="500">
    <ItemsControl ItemsSource="{Binding Columns}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <DataTemplate.Resources>
                    <BooleanToVisibilityConverter x:Key="BoolToVisConverter"/>
                </DataTemplate.Resources>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="20"/>
                        <ColumnDefinition Width="50"/>
                        <ColumnDefinition/>
                        <ColumnDefinition Width="100"/>
                        <ColumnDefinition Width="25"/>
                        <ColumnDefinition Width="25"/>
                    </Grid.ColumnDefinitions>

                    <!-- This is your Key image, I used a rectangle instead, you can change it -->
                    <Rectangle Fill="Yellow" Visibility="{Binding IsPrimaryKey, Converter={StaticResource BoolToVisConverter}}"  Margin="2"/>

                    <CheckBox IsChecked="{Binding IsSelected}" Grid.Column="1"/>

                    <TextBlock Text="{Binding Name}" Grid.Column="2"/>

                    <ComboBox ItemsSource="{Binding SortOrders}" SelectedItem="{Binding SortOrder}" Grid.Column="3" Margin="2"/>

                    <Button Content="Up" Grid.Column="4" Margin="2"
                            Command="{Binding DataContext.MoveUpCommand, RelativeSource={RelativeSource FindAncestor, AncestorType=ItemsControl}}"
                            CommandParameter="{Binding}"/>

                    <Button Content="Down" Grid.Column="5" Margin="2"
                            Command="{Binding DataContext.MoveDownCommand, RelativeSource={RelativeSource FindAncestor, AncestorType=ItemsControl}}"
                            CommandParameter="{Binding}"/>

                </Grid>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Window>

代码背后:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using InduraClientCommon.MVVM;
using System.Collections.ObjectModel;

namespace WpfApplication4
{
    public partial class Window9 : Window
    {
        public Window9()
        {
            InitializeComponent();

            var vm = new ColumnListViewModel();
            vm.Columns.Add(new ColumnViewModel() { IsPrimaryKey = true, Name = "Customer ID", SortOrder = SortOrder.Ascending });
            vm.Columns.Add(new ColumnViewModel() {Name = "Customer Name", SortOrder = SortOrder.Descending});
            vm.Columns.Add(new ColumnViewModel() {Name = "Customer Age", SortOrder = SortOrder.Unsorted});

            DataContext = vm;
        }
    }
}

视图模型:

 public class ColumnListViewModel: ViewModelBase
    {
        private ObservableCollection<ColumnViewModel> _columns;
        public ObservableCollection<ColumnViewModel> Columns
        {
            get { return _columns ?? (_columns = new ObservableCollection<ColumnViewModel>()); }
        }

        private DelegateCommand<ColumnViewModel> _moveUpCommand;
        public DelegateCommand<ColumnViewModel> MoveUpCommand
        {
            get { return _moveUpCommand ?? (_moveUpCommand = new DelegateCommand<ColumnViewModel>(MoveUp, x => Columns.IndexOf(x) > 0)); }
        }

        private DelegateCommand<ColumnViewModel> _moveDownCommand;
        public DelegateCommand<ColumnViewModel> MoveDownCommand
        {
            get { return _moveDownCommand ?? (_moveDownCommand = new DelegateCommand<ColumnViewModel>(MoveDown, x => Columns.IndexOf(x) < Columns.Count)); }
        }

        private void MoveUp(ColumnViewModel item)
        {
            var index = Columns.IndexOf(item);
            Columns.Move(index, index - 1);
            MoveUpCommand.RaiseCanExecuteChanged();
            MoveDownCommand.RaiseCanExecuteChanged();
        }

        private void MoveDown(ColumnViewModel item)
        {
            var index = Columns.IndexOf(item);
            Columns.Move(index, index + 1);
            MoveUpCommand.RaiseCanExecuteChanged();
            MoveDownCommand.RaiseCanExecuteChanged();
        }
    }

    public class ColumnViewModel: ViewModelBase
    {
        private bool _isPrimaryKey;
        public bool IsPrimaryKey
        {
            get { return _isPrimaryKey; }
            set
            {
                _isPrimaryKey = value;
                NotifyPropertyChange(() => IsPrimaryKey);
            }
        }

        private bool _isSelected;
        public bool IsSelected
        {
            get { return _isSelected; }
            set
            {
                _isSelected = value;
                NotifyPropertyChange(() => IsSelected);
            }
        }

        private string _name;
        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                NotifyPropertyChange(() => Name);
            }
        }

        private List<SortOrder> _sortOrders;
        public List<SortOrder> SortOrders
        {
            get { return _sortOrders ?? (_sortOrders = Enum.GetValues(typeof(SortOrder)).OfType<SortOrder>().ToList()); }
        }

        private SortOrder _sortOrder;
        public SortOrder SortOrder
        {
            get { return _sortOrder; }
            set
            {
                _sortOrder = value;
                NotifyPropertyChange(() => SortOrder);
            }
        }
    }

    public enum SortOrder {Unsorted, Ascending, Descending}
}

这就是我的屏幕中的样子:

enter image description here

正如您在上面的示例中所看到的,我无法在代码中操作或创建UI元素,因为它实际上并不是必需的。只要您需要与屏幕中显示的信息进行交互,就可以与ViewModel进行交互,而不是View。这是WPF实现的UI和应用程序逻辑之间关注点的明确分离,这在其他框架中是完全不存在的。在WPF中执行任何类型的N元素UI时,请将此方法视为事实上的默认值。

修改

此方法相对于classic的优势:

  
      
  • 无需在代码中操作复杂的WPF类(I.E UI元素)以便从屏幕显示/获取数据(只需简单,简单   属性和INotifyPropertyChanged)
  •   
  • 更好地扩展(UI可以是任何东西,只要它尊重ViewModel属性,您可以将ComboBox更改为旋转的3d   每只脚都有排序的粉红色大象。
  •   
  • 无需浏览可视树,找到位于上帝知道位置的元素。
  •   
  • 无需foreach任何事情。只是一个简单的Select,可以将您的数据(从您获得的数据源)转换为   ViewModel列表。
  •   

结论:如果使用WPF方法,WPF比现有的其他任何东西都简单得多,而且更好。

答案 2 :(得分:1)

您正在更改RowDefinition的顺序,这不是您想要的。您希望将元素分配更改为行,这由Grid.Row attached property

确定

我会将属于每一行的所有控件放在一个容器中(每行一个),然后使用Grid.SetRow来更改容器。请参阅how to change the grid row of the control from code behind in wpf