コマンドの実装例をメモします。
<Window x:Class="WpfApplication5.CommandTest"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication5"
mc:Ignorable="d"
Title="CommandTest" Height="150" Width="300">
<Grid>
<TextBox x:Name="textBox"
HorizontalAlignment="Left"
Height="23"
Text="{Binding MyText}"
Width="120"/>
<Button x:Name="button"
Content="Clear Text"
Command="{Binding ClearText}"
CommandParameter="{Binding ElementName=textBox}"
HorizontalAlignment="Left"
Width="75"
Margin="125,0,0,0" Height="23"/>
</Grid>
</Window>
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace WpfApplication5
{
public partial class CommandTest : Window
{
public CommandTest()
{
InitializeComponent();
MyData data = new MyData();
data.MyText = "123 test";
this.DataContext = data;
}
}
public class MyData : NotificationObject
{
private string _MyText;
public string MyText
{
get
{
return _MyText;
}
set
{
this._MyText = value;
this.OnPropertyChanged();
}
}
private ClearTextCommand _ClearText;
public ClearTextCommand ClearText {
get{
if(_ClearText == null)
{
_ClearText = new ClearTextCommand();
}
return _ClearText;
}
}
}
public class ClearTextCommand : ICommand
{
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
TextBox textBox = parameter as TextBox;
textBox?.Clear();
}
}
}
0 件のコメント:
コメントを投稿