Использование команд в WPF
Как правильно создать Command
, чтобы при нажатии на кнопку, текст улетал в TextBlock
из TextBox
. Пробовал, но не получалось. Решил понизить сложность и просто вывести MessageBox
, но опять ничего
MainWindow.xaml:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0" HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Vertical">
<TextBox Text="{Binding Path=SynchronizedText, UpdateSourceTrigger=PropertyChanged, Mode=OneWayToSource}" Height="30" BorderBrush="Blue">
<TextBox.Resources>
<Style TargetType="Border">
<Setter Property="CornerRadius" Value="10"/>
</Style>
</TextBox.Resources>
</TextBox>
<Border BorderBrush="Black" BorderThickness="1" Width="130" Height="30" CornerRadius="10" Margin="0,10,0,0">
<TextBlock Text="{Binding Path=SynchronizedText, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
</StackPanel>
<StackPanel Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Vertical">
<TextBox Text="" Height="30" BorderBrush="Blue">
<TextBox.Resources>
<Style TargetType="Border">
<Setter Property="CornerRadius" Value="10"/>
</Style>
</TextBox.Resources>
</TextBox>
<Border BorderBrush="Black" BorderThickness="1" Width="130" Height="30" CornerRadius="10" Margin="0,10,0,0">
<TextBlock Text="" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
<Button Content="ПЕРЕСЛАТЬ" Width="130" Height="30" Margin="0,10" Command="{Binding command}"/>
</StackPanel>
</Grid>
MainWindow.xaml.cs:
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainWindowVM();
}
BaseVM.cs:
class BaseVM : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
MainWindowVM.cs:
class MainWindowVM : BaseVM
{
private string _synchronizedText;
public string SynchronizedText
{
get => _synchronizedText;
set
{
_synchronizedText = value;
OnPropertyChanged(nameof(SynchronizedText));
}
}
public ICommand command { get; set; }
public MainWindowVM()
{
command = new Command();
}
private bool canExecuteMethod(object parameter)
{
return true;
}
private void ExecuteMethod(object parameter)
{
MessageBox.Show("OK","OK",MessageBoxButton.OK, MessageBoxImage.Information);
}
}
Command.cs:
class Command : ICommand
{
public event EventHandler CanExecuteChanged;
Action<object> executeMethod;
Func<object, bool> canExecuteMethod;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
executeMethod(parameter);
}
}