Как передать несколько параметров в WPF Command с помощью кнопки? - PullRequest
0 голосов
/ 05 ноября 2019

В настоящее время мой код выглядит следующим образом:

<Button Command="{Binding DrinkCommand}" CommandParameter="Capuccino" Style="{StaticResource DrinkButton}">
    <TextBlock>Capuccino</TextBlock>
</Button>
<Button Command="{Binding DrinkWithSugarCommand}" CommandParameter="Capuccino" Style="{StaticResource DrinkButton}">
    <TextBlock>Capuccino + sugar</TextBlock>
</Button>

Вы можете видеть, что у меня есть другой RelayCommand для капучино с сахаром и без сахара.

Я бы хотел добавить опцию добавления дополнительного молока. Однако, чем я получу:

DrinkCommand,

DrinkWithSugarCommand,

DrinkWithMilkCommand,

DrinkWithSugarAndMilkCommand.

Есть ли способ сообщить DrinkCommand, что я хочу напиток (капучино) с сахаром и / или молоком?

Ответы [ 3 ]

4 голосов
/ 05 ноября 2019

Вы можете создать класс для хранения ваших различных параметров команды и использовать его следующим образом:

<Button Content="Capuccino + sugar" Command="{Binding DrinkCommand}">
    <Button.CommandParameter>
        <wpfapp1:MyCommandParameters Milk="false" Sugar="true"/>
    </Button.CommandParameter>
</Button>

Ваш класс будет выглядеть как

public class MyCommandParameters {
    public bool Milk { get; set; }
    public bool Sugar { get; set; }
}

, и вы можете использовать его в своей командекод, в котором он будет передан в качестве аргумента.

0 голосов
/ 06 ноября 2019

вы можете использовать одну команду с одним параметром, который может быть проанализирован в методе команды.

Такой параметр может иметь тип enum, который объявлен с атрибутом Flags witrh:

[Flags]
private enum Tastes
{
    None = 0,
    Sugar = 1,
    Milk = 1 << 1,
    Capuccino = 1 << 2
}

xaml:

<Button Command="{Binding DrinkCommand}" CommandParameter="Capuccino" 
        Content="Capuccino" Style="{StaticResource DrinkButton}"/>
<Button Command="{Binding DrinkCommand}" CommandParameter="Capuccino, Sugar"
        Content="Capuccino + sugar" Style="{StaticResource DrinkButton}"/>
<Button Command="{Binding DrinkCommand}" CommandParameter="Milk" 
        Content="Milk" Style="{StaticResource DrinkButton}"/>
<Button Command="{Binding DrinkCommand}" CommandParameter="Milk, Sugar" 
        Content="Milk + sugar" Style="{StaticResource DrinkButton}"/>

метод команды:

private void Drink(object args)
{
    string x = (string)args;
    if (x != null)
    {
        Tastes t = (Tastes)Enum.Parse(typeof(Tastes), x);
        if (t.HasFlag(Tastes.Sugar))
        {
            Console.WriteLine("sweet");
        }
    }
}
0 голосов
/ 05 ноября 2019

Существует несколько способов раскрыть ваши потребности, после использования выпадающего списка для выбора типа команды и кнопки для отправки запроса:

Xaml

    <Window x:Class="CommandNameSpace.Views.MainWindowView"
                 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">

        <Grid x:Name="MainGrid">
            <Canvas >
                <StackPanel VerticalAlignment="Center">
                    <ComboBox  ItemsSource="{Binding LisCommandType, Mode=TwoWay}"  SelectedItem="{Binding SelectedCommandType, Mode=TwoWay}" >
                        <ComboBox.ItemTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding Value}"/>
                            </DataTemplate>
                        </ComboBox.ItemTemplate>
                    </ComboBox>
                </StackPanel>

           <StackPanel VerticalAlignment="Center">
                    <Button x:Name="cmdCommand" IsDefault="True" Content="Commander" Command = "{Binding OrderCommand}" CommandParameter = "null"/>
           </StackPanel>
        </Canvas >
       </Grid>
    </Window >

Основной класс

namespace CommandNameSpace
{
   public class MainCalss
   {
        public BaseCommand<string> OrderCommand { get; private set; }
        private Dictionary<string, string> _selectedCommandType = new Dictionary<string, string>();
        private KeyValuePair<string, string> _selectedLanguage;

        public ServicesControlViewModel()
        {
            OrderCommand = new BaseCommand<string>(cmdOrderCommand);

            LisCommandType.Add("DrinkCommand", "Drink");
            LisCommandType.Add("DrinkWithSugarCommand", "Drink With Sugar");
            LisCommandType.Add("DrinkWithMilkCommand", "Drink With Milk");
            LisCommandType.Add("DrinkWithSugarAndMilkCommand", "Drin kWith Sugar And Milk");

            SelectedCommandType = new KeyValuePair<string, string>("DrinkCommand", "Drink");
        }

        public Dictionary<string, string> LisCommandType
        {
            get
            {
            return _liscommandType;
            }
            set
            {
            _liscommandType = value;
            }
        }

        public KeyValuePair<string, string> SelectedCommandType
        {
            get
            {
            return _selectedCommandType;
            }
            set
            {
            _selectedCommandType = value;
            }
        }

        private void cmdOrderCommand(string paramerter)
        {
            switch (SelectedCommandType)
            {
                case "DrinkCommand":
                    Instruction for DrinkCommand type

                    break;
                case "DrinkWithSugarCommand":
                    Instruction for DrinkCommand type

                    break;
                case "DrinkWithMilkCommand":
                    Instruction for DrinkCommand type

                    break;
                case "DrinkWithSugarAndMilkCommand":
                    Instruction for DrinkCommand type

                    break;
            }
        }
}

Зрение зрения

MainCalss MainCl = new MainCalss();
MainWindowView MainV = new MainWindowView();
MainV.Datacontext = MainCl;
MainV.ShowDialog(); 

Cordialy

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...