Вызвать команду на столбце DataGrid одним щелчком мыши - PullRequest
0 голосов
/ 30 марта 2020

Я хотел бы создать гиперссылку-столбец в wpf, но с привязкой к команде вместо uri.

 <DataGridTemplateColumn Header="{lex:Loc newmaterialnumber}" Width="*">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock TextDecorations="Underline" Text="{Binding NewMaterialnumber}"  Cursor="Hand" VerticalAlignment="Center" HorizontalAlignment="Left">
                            <TextBlock.InputBindings>
                                <MouseBinding MouseAction="LeftClick" Command="{Binding DataContext.OpenNewMaterialnumberCommand, RelativeSource={RelativeSource AncestorType={x:Type local:ArticleInfoSearchWindow}}}" />
                            </TextBlock.InputBindings>
                        </TextBlock>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>

Это прекрасно работает, но мне нужно сначала выбрать строку, прежде чем я смогу щелкнуть ссылку. Это было бы достижимо с помощью datatrigger, который устанавливает строку, выбранную при наведении, но я действительно не хочу выбирать строку при наведении.

Есть идеи получше?

1 Ответ

0 голосов
/ 06 мая 2020

Я придумал это решение. Прежде всего создайте новый DataGridCommandColumn, унаследованный от DataGridBoundColumn.

public class DataGridCommandColumn : DataGridBoundColumn
{
    [Bindable(true)]
    public ICommand Command
    {
        get => (ICommand)GetValue(CommandProperty);
        set => SetValue(CommandProperty, value);
    }

    public static readonly DependencyProperty CommandProperty = DependencyProperty.Register(
        nameof(Command),
        typeof(ICommand),
        typeof(DataGridCommandColumn));

    [Bindable(true)]
    public int FontSize
    {
        get => (int)GetValue(FontSizeProperty);
        set => SetValue(FontSizeProperty, value);
    }

    public static readonly DependencyProperty FontSizeProperty = DependencyProperty.Register(
        nameof(FontSize),
        typeof(int),
        typeof(DataGridCommandColumn));


    protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem)
    {
        throw new NotImplementedException();
    }

    protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
    {
        var button = new Button();

        button.SetResourceReference(FrameworkElement.StyleProperty, "ToolButonWithDisabledRecognizesAccessKey");
        button.SetResourceReference(Control.ForegroundProperty, "PrimaryHueMidBrush");

        button.Height = 20;
        button.VerticalContentAlignment = VerticalAlignment.Top;
        button.HorizontalContentAlignment = HorizontalAlignment.Left;
        button.HorizontalAlignment = HorizontalAlignment.Left;
        button.Padding = new Thickness(0);
        button.FontWeight = FontWeights.Normal;
        if (FontSize != 0)
        {
            button.FontSize = FontSize;
        }


        button.Click += Button_Click;
        BindingOperations.SetBinding(button, ContentControl.ContentProperty, Binding);

        return button;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        if (Command == null)
        {
            return;
        }

        if (Command.CanExecute(null))
        {
            Command.Execute(null);
        }
    }
}

Затем создайте прокси:

public class ViewModelProxy : Freezable
{
    protected override Freezable CreateInstanceCore()
    {
        return new ViewModelProxy();
    }

    public ViewModelBase ViewModel
    {
        get => (ViewModelBase)GetValue(ViewModelProperty);
        set => SetValue(ViewModelProperty, value);
    }

    public static readonly DependencyProperty ViewModelProperty = 
        DependencyProperty.Register("ViewModel", typeof(ViewModelBase), typeof(ViewModelProxy), new UIPropertyMetadata(null));
}

Позже вы сможете использовать его:

<utility:ViewModelProxy  x:Key="ViewModelProxy" ViewModel="{Binding}" />

<controls:DataGridCommandColumn Header="{lex:Loc submissionnumber}" Binding="{Binding SubmissionNumber}"  Command="{Binding ViewModel.OpenReceivableSubmissionNumberCommand,  Source={StaticResource ViewModelProxy}}" Width="Auto"  />
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...