Типы
ButtonBase
имеют встроенные свойства зависимостей ICommand Command
и object CommandParameter
. Вы можете создать свои собственные несколькими способами, но вот два моих главных предложения.
собственный CommandableTextBox
элемент управления, который в основном добавляет 2 элемента зависимостей к элементу управления: ICommand Command
и object CommandParameter
.
Или вы можете создать присоединяемое свойство (что я очень рекомендую), которое позволяет вам добавлять команду и параметр команды для определенных типов.Это более сложная предварительная работа, но гораздо более понятная и простая в использовании, и вы можете добавить ее к существующим TextBox
элементам управления.
Я написал присоединяемый TextChangedCommand для вас.Вот как это выглядит в XAML.В моем решении я добавил пространство имен в XAML как таковое, но вам нужно убедиться, что ваш путь правильный для вашего.
xmlns:attachable="clr-namespace:Question_Answer_WPF_App.Attachable"
<TextBox attachable:Commands.TextChangedCommand="{Binding MyCommand}"
attachable:Commands.TextChangedCommandParameter="{Binding MyCommandParameter}"/>
А вот ПрисоединяемыйНедвижимость для вас:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace Question_Answer_WPF_App.Attachable
{
public class Commands
{
public static ICommand GetTextChangedCommand(TextBox textBox)
=> (ICommand)textBox.GetValue(TextChangedCommandProperty);
public static void SetTextChangedCommand(TextBox textBox, ICommand command)
=> textBox.SetValue(TextChangedCommandProperty, command);
public static readonly DependencyProperty TextChangedCommandProperty =
DependencyProperty.RegisterAttached(
"TextChangedCommand",
typeof(ICommand),
typeof(Commands),
new PropertyMetadata(null, new PropertyChangedCallback((s, e) =>
{
if (s is TextBox textBox && e.NewValue is ICommand command)
{
textBox.TextChanged -= textBoxTextChanged;
textBox.TextChanged += textBoxTextChanged;
void textBoxTextChanged(object sender, TextChangedEventArgs textChangedEventArgs)
{
var commandParameter = GetTextChangedCommandParameter(textBox);
if (command.CanExecute(commandParameter))
command.Execute(commandParameter);
}
}
})));
public static object GetTextChangedCommandParameter(TextBox textBox)
=> textBox.GetValue(TextChangedCommandParameterProperty);
public static void SetTextChangedCommandParameter(TextBox textBox, object commandParameter)
=> textBox.SetValue(TextChangedCommandParameterProperty, commandParameter);
public static readonly DependencyProperty TextChangedCommandParameterProperty =
DependencyProperty.RegisterAttached("TextChangedCommandParameter", typeof(object), typeof(Commands), new PropertyMetadata(null));
}
}