可視性、ツールチップ、およびコマンドのデータバインディングを使用して、テンプレート化されたボタン コントロールを作成しようとしています。Visibility バインディングはツールチップと同様に機能しますが、Command は機能しません。ビューモデルを挿入してビューに関連付けるプロセスは別のプロセスであり、他のデータ バインディングは機能しているので、適切に機能していると確信しています。
リソース ディクショナリ:
<Converters:BoolToVisibilityConverter x:Key="boolVisibilityConverter" />
<Style TargetType="local:ImageButton">
<Setter Property="Visibility" Value="{Binding FallbackValue=Visible, Path=ToolIsAvailable, Converter={StaticResource boolVisibilityConverter} }"/>
<Setter Property="Command" Value="{Binding ButtonCommand}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:ImageButton">
<Grid>
<Image Source="{TemplateBinding Image}"
ToolTipService.ToolTip="{Binding ToolName}" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
テンプレート化されたコントロール
public class MyButton: ImageButton
{
public MyButton(MyCommandViewModel viewmodel)
{
this.DefaultStyleKey = typeof(ImageButton);
this.Image = new BitmapImage(new Uri("/MyProject;component/Themes/myimage.png", UriKind.Relative));
this.DataContext = viewmodel;
}
}
そしてビューモデルで
public MyCommandViewModel()
: base("My Tool", true)
{
}
public class CommandViewModel
{
public CommandViewModel(string toolName, bool isAvailable)
{
ToolIsAvailable = isAvailable;
ToolName = toolName;
_buttoncommand = new DelegateCommand(() =>
{
ExecuteCommand();
},
() => { return CanExecute; });
}
private bool _canExecute = true;
public bool CanExecute
{
get { return _canExecute; }
set
{
_canExecute = value;
OnPropertyChanged("CanExecute");
if (_command != null) _command.RaiseCanExecuteChanged();
}
}
private DelegateCommand _buttoncommand;
public ICommand ButtonCommand
{
get { return _buttoncommand; }
}
protected virtual void ExecuteCommand()
{
}
public bool ToolIsAvailable
{
get { return _toolIsReady; }
set { _toolIsReady = value; OnPropertyChanged("ToolIsAvailable"); }
}
public string ToolName
{
get { return _toolName; }
set { _toolName = value; OnPropertyChanged("ToolName"); }
}
}
他のデータ バインディングは正しく機能しているのに、コマンド データ バインディングは機能していないのはなぜですか。この同様の投稿を見つけまし た WPF でテンプレート化されたボタンのコマンドをオーバーライドする 代わりにグリッド コントロールをテンプレート化し、RoutedCommands を使用する必要がありますか? Silverlight がコマンド バインディングを他のバインディングとは異なる方法で扱う理由がよくわからないので、コードにバグがあるだけだと思います。