WPFでMVVMデザインパターンを使用してプログラムでデータグリッド行のフォーカスを選択および設定する方法

プラボダ

データグリッドを備えた単純なWPFアプリケーションがあります。ボタンをクリックしたら、フォーカスデータグリッドの行を選択して設定します。行が選択されたら、キーボードの上下矢印キーを使用して、選択された(フォーカスされた)行を変更する必要があります。最も無力なことは、MVVMデザインパターンでこれを実行したいということです。私のアプリケーションは以下の通りです。

Item.cs モデルは以下の通りです:

public class Item
{
    public string ItemCode { get; set; }
    public string ItemName { get; set; }
    public double ItemPrice { get; set; }

    public Item(string itemCode, string itemName, double itemPrice)
    {
        this.ItemCode = itemCode;
        this.ItemName = itemName;
        this.ItemPrice = itemPrice;
    }
}

ItemViewModel.cs 以下のとおりです。

public class ItemsViewModel : INotifyPropertyChanged
{
    private List<Item> _items;

    public List<Item> ItemsCollection
    {
        get { return this._items; }
        set
        {
            _items = value;
            OnPropertyChanged(nameof(ItemsCollection));
        }
    }

    public ItemsViewModel()
    {
        this.ItemsCollection = new List<Item>();
        //Add default items
        this.ItemsCollection.Add(new Item("I001", "Text Book", 10));
        this.ItemsCollection.Add(new Item("I002", "Pencil", 20));
        this.ItemsCollection.Add(new Item("I003", "Bag", 15));
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

MainWindowViewModel.cs 以下のように:

public class MainWindowViewModel : INotifyPropertyChanged
{
    public ICommand SelectRow { get; private set; }

    public MainWindowViewModel()
    {
        this.SelectRow = new RelayCommand(this.SelectGridRow, o => true);
    }

    private void SelectGridRow(object param)
    {
        //TODO: Code should goes here
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

RelayCommand.csコマンドバインディングを処理するために、次のよう記述しました

public class RelayCommand : ICommand
{
    #region Fields

    /// <summary>
    /// Encapsulated the execute action
    /// </summary>
    private Action<object> execute;

    /// <summary>
    /// Encapsulated the representation for the validation of the execute method
    /// </summary>
    private Predicate<object> canExecute;

    #endregion // Fields

    #region Constructors

    /// <summary>
    /// Initializes a new instance of the RelayCommand class
    /// Creates a new command that can always execute.
    /// </summary>
    /// <param name="execute">The execution logic.</param>
    public RelayCommand(Action<object> execute)
        : this(execute, DefaultCanExecute)
    {
    }

    /// <summary>
    /// Initializes a new instance of the RelayCommand class
    /// Creates a new command.
    /// </summary>
    /// <param name="execute">The execution logic.</param>
    /// <param name="canExecute">The execution status logic.</param>
    public RelayCommand(Action<object> execute, Predicate<object> canExecute)
    {
        if (execute == null)
        {
            throw new ArgumentNullException("execute");
        }

        if (canExecute == null)
        {
            throw new ArgumentNullException("canExecute");
        }

        this.execute = execute;
        this.canExecute = canExecute;
    }

    #endregion // Constructors

    #region ICommand Members

    /// <summary>
    /// An event to raise when the CanExecute value is changed
    /// </summary>
    /// <remarks>
    /// Any subscription to this event will automatically subscribe to both 
    /// the local OnCanExecuteChanged method AND
    /// the CommandManager RequerySuggested event
    /// </remarks>
    public event EventHandler CanExecuteChanged
    {
        add
        {
            CommandManager.RequerySuggested += value;
            this.CanExecuteChangedInternal += value;
        }

        remove
        {
            CommandManager.RequerySuggested -= value;
            this.CanExecuteChangedInternal -= value;
        }
    }

    /// <summary>
    /// An event to allow the CanExecuteChanged event to be raised manually
    /// </summary>
    private event EventHandler CanExecuteChangedInternal;

    /// <summary>
    /// Defines if command can be executed
    /// </summary>
    /// <param name="parameter">the parameter that represents the validation method</param>
    /// <returns>true if the command can be executed</returns>
    public bool CanExecute(object parameter)
    {
        return this.canExecute != null && this.canExecute(parameter);
    }

    /// <summary>
    /// Execute the encapsulated command
    /// </summary>
    /// <param name="parameter">the parameter that represents the execution method</param>
    public void Execute(object parameter)
    {
        this.execute(parameter);
    }

    #endregion // ICommand Members

    /// <summary>
    /// Raises the can execute changed.
    /// </summary>
    public void OnCanExecuteChanged()
    {
        EventHandler handler = this.CanExecuteChangedInternal;
        if (handler != null)
        {
            //DispatcherHelper.BeginInvokeOnUIThread(() => handler.Invoke(this, EventArgs.Empty));
            handler.Invoke(this, EventArgs.Empty);
        }
    }

    /// <summary>
    /// Destroys this instance.
    /// </summary>
    public void Destroy()
    {
        this.canExecute = _ => false;
        this.execute = _ => { return; };
    }

    /// <summary>
    /// Defines if command can be executed (default behaviour)
    /// </summary>
    /// <param name="parameter">The parameter.</param>
    /// <returns>Always true</returns>
    private static bool DefaultCanExecute(object parameter)
    {
        return true;
    }
}

私はItemView.xaml以下のようなユーザーコントロールを持っています:

<UserControl x:Class="DataGrid_FocusRow.ItemView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:DataGrid_FocusRow"
         mc:Ignorable="d" 
         d:DesignHeight="450" d:DesignWidth="800">
<Grid>
    <StackPanel Orientation="Vertical">
        <DataGrid x:Name="grdItems" ItemsSource="{Binding ItemsCollection}" AutoGenerateColumns="False" ColumnWidth="*">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Item Code" Binding="{Binding ItemCode}" />
                <DataGridTextColumn Header="Item Name" Binding="{Binding ItemName}" />
                <DataGridTextColumn Header="Item Price" Binding="{Binding ItemPrice}" />
            </DataGrid.Columns>
        </DataGrid>
    </StackPanel>
</Grid>

MainWindow.xamlは以下の通りです:

<Window x:Class="DataGrid_FocusRow.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:DataGrid_FocusRow"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<StackPanel>
    <local:ItemView/>

    <Button Command="{Binding SelectRow}">Select Row</Button>
</StackPanel>

誰かがこれを手伝ってくれませんか。

更新:「SelectedIndex」と「SelectedItem」を設定して、すでに試しました。データグリッドの行を選択します。ただし、特定の行にフォーカスを設定するわけではありません。そのため、キーボードの上下キーで選択を変更することはできません。

プラボダ

私は方法を発見しました。次のSelectingItemAttachedProperty.csクラスで行選択を処理しました

public class SelectingItemAttachedProperty
{
    public static readonly DependencyProperty SelectingItemProperty = DependencyProperty.RegisterAttached("SelectingItem", typeof(Item), typeof(SelectingItemAttachedProperty), new PropertyMetadata(default(Item), OnSelectingItemChanged));

    public static Item GetSelectingItem(DependencyObject target)
    {
        return (Item)target.GetValue(SelectingItemProperty);
    }

    public static void SetSelectingItem(DependencyObject target, Item value)
    {
        target.SetValue(SelectingItemProperty, value);
    }

    static void OnSelectingItemChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        var grid = sender as DataGrid;
        if (grid == null || grid.SelectedItem == null)
            return;

        grid.Dispatcher.InvokeAsync(() =>
        {
            grid.UpdateLayout();
            grid.ScrollIntoView(grid.SelectedItem, null);
            var row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(grid.SelectedIndex);
            row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        });
    }
}

ItemView.xamlユーザーコントロール私は私のボタンを追加し、設定していますSelectingItemAttachedProperty私たちは以下のように上記実施していること。

<UserControl x:Class="DataGrid_FocusRow.ItemView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:DataGrid_FocusRow"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
        <StackPanel Orientation="Vertical">
            <DataGrid x:Name="grdItems" ItemsSource="{Binding ItemsCollection}" AutoGenerateColumns="False" ColumnWidth="*" 
                      SelectedItem="{Binding SelectingItem}" local:SelectingItemAttachedProperty.SelectingItem="{Binding SelectingItem}">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="Item Code" Binding="{Binding ItemCode}" />
                    <DataGridTextColumn Header="Item Name" Binding="{Binding ItemName}" />
                    <DataGridTextColumn Header="Item Price" Binding="{Binding ItemPrice}" />
                </DataGrid.Columns>
            </DataGrid>
            <Button Command="{Binding SelectRow}">Select Row</Button>
        </StackPanel>
    </Grid>
</UserControl>

次にSelectGridRow()、ビューモデルのメソッドで選択したアイテムを次のように設定します

public class ItemsViewModel : INotifyPropertyChanged
{
    private Item _selectingItem;
    private List<Item> _items;

    public Item SelectingItem
    {
        get { return this._selectingItem; }
        set
        {
            this._selectingItem = value;
            OnPropertyChanged(nameof(this.SelectingItem));
        }
    }

    public List<Item> ItemsCollection
    {
        get { return this._items; }
        set
        {
            _items = value;
            OnPropertyChanged(nameof(ItemsCollection));
        }
    }

    public ICommand SelectRow { get; private set; }

    public ItemsViewModel()
    {
        this.ItemsCollection = new List<Item>();
        //Add default items
        this.ItemsCollection.Add(new Item("I001", "Text Book", 10));
        this.ItemsCollection.Add(new Item("I002", "Pencil", 20));
        this.ItemsCollection.Add(new Item("I003", "Bag", 15));

        this.SelectRow = new RelayCommand(this.SelectGridRow, o => true);
    }

    private void SelectGridRow(object param)
    {
        this.SelectingItem = this.ItemsCollection[0];
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

Related 関連記事

ホットタグ

アーカイブ