動作環境
Windows 7 Pro (32bit)
Microsoft Visual Studio 2017 Community
MVVMにてICommandを使う実装を試そうとしたら、CanExecute()の実装がないためエラーとなった。
ICommand関連は未消化だった。
CanExecute()について調べた。
@gushwell さんのページが参考になりました。
http://gushwell.ldblog.jp/archives/52321430.html
テキスト文字列がnullや空文字列の場合はボタンを押せないという実装として使われています。
PasswordBoxへのbindingを試した。
MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace _170623_t1800_ICommand_password
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
public class MyCommand : ICommand
{
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public bool CanExecute(object parameter)
{
string text = parameter as string;
return (text == "123456");
}
public void Execute(object parameter)
{
MessageBox.Show("Genie in the Lamp");
}
}
}
MainWindow.xaml
<Window x:Class="_170623_t1800_ICommand_password.MainWindow"
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:_170623_t1800_ICommand_password"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:MyCommand x:Key="myCommand"/>
</Window.Resources>
<Grid>
<StackPanel Margin="20">
<PasswordBox Height="24" Name="passBox1"/>
<Button Content="Genie" Height="24" Name="button1" Width="75"
Command="{Binding Mode=OneWay, Source={StaticResource myCommand}}"
CommandParameter="{Binding ElementName=passBox1, Path=Password}"/>
</StackPanel>
</Grid>
</Window>
"123456"と入力すればボタンが押下可能になり、アラジンの魔法のランプのGenieが登場。
のはずがそうはならなかった。
string text = parameter as string;
のtextはnullになった。
以下を見つけました。
https://garafu.blogspot.jp/2014/09/wcf-passwordbox.html
WPF の PasswordBox は セキュリティ上の問題から直接データバインドすることができません。 …が、セキュリティ上の問題を承知したうえで、それでもデータバインドしたい、簡便さを優先したい場合があると思います。 今回は、セキュリティ上の問題を承知したうえで、データバインドを実現する方法をまとめます。