Как к `s:String` привязать `TextBox`

Рейтинг: 0Ответов: 1Опубликовано: 26.03.2023

Мне необходимо передать команде аргумент в виде массива. Который хранит строки, делаю это так:

<TextBox Text = "Я содержу текст"/>
<TextBox Text = "Я тоже"/>

<!-- Теперь кнопка отправки-->
<Button Content = "Отправить текст из TextBox в команду при нажатии"
        Command = "{Binding SendCommand}">
    <Button.CommandParameter>

        <x:Array xmlns:s = "clr-namespace:System; assembly = mscorlib"
                 Type = "s:String">

            <s:String> Как это мне привязать к TextBox?</s:String>
        </x:Array>
    </Button.CommandParameter>
</Button>

В MainWindow.xaml.cs или в модели указываем команду:

// Создаём RelayCommand и импортируем

public ICommand SendCommand => new RelayCommand(obj => {
    obj = (Array)obj; // Ожидаю массив
    obj.GetValue(0); // Получаю данные
});

RelayCommand:

public class RelayCommand : ICommand
{
    private Action<object> execute;
    private Func<object, bool> canExecute;

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
    {
        this.execute = execute;
        this.canExecute = canExecute;
    }

    public bool CanExecute(object parameter)
    {
        return this.canExecute == null || this.canExecute(parameter);
    }

    public void Execute(object parameter)
    {
        this.execute(parameter);
    }
}

Как к s:String привязать TextBox?

Ответы

▲ 0Принят

Используйте ElementName

<TextBox x:Name="myTextBox" Text="Я содержу текст"/>

<Button Content="Отправить текст из TextBox в команду при нажатии"
        Command="{Binding SendCommand}"
        CommandParameter="{Binding Text, ElementName=myTextBox}">
</Button>

Для нескольких значений потребуется MultiBinding и IMultiValueConverter

public class StringsToArrayConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        => values?.Cast<string>().ToArray() ?? Array.Empty<string>();

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        => throw new NotSupportedException();
}

Подключаю конвертер

<Window.Resources>
    <StringsToArrayConverter x:Key="StringsToArrayConverter"/>
</Window.Resources>

Делаю привязку

<TextBox x:Name="myTextBox1" Text="Я содержу текст"/>
<TextBox x:Name="myTextBox2" Text="Я тоже"/>

<Button Content="Отправить текст из TextBox в команду при нажатии"
        Command="{Binding SendCommand}">
    <Button.CommandParameter>
        <MultiBinding Converter="{StaticResource StringsToArrayConverter}">
            <Binding Path="Text" ElementName="myTextBox1"/>
            <Binding Path="Text" ElementName="myTextBox2"/>
        </MultiBinding>
    </Button.CommandParameter>
</Button>