下載app免費領取會員
在WPF里的Button有一個可以綁定的Command的屬性,只要綁定好這個屬性以后,只要你ClickButton就
會運行這個命令,但這時我們可以考慮一下這個問題,為什么是Click來觸發(fā)呢?為什么不是右鍵單擊來觸發(fā)呢,
下面研究一下,怎么能寫一個右鍵單機能觸發(fā)的命令:
首先現(xiàn)有的Button肯定是不行了,所以自己寫一個TButton ,它繼承自Button
public class TButton:Button
{
public static readonly DependencyProperty TCommandParameterProperty = DependencyProperty.Register("TCommandParameter", typeof(object), typeof(TButton));
public static readonly DependencyProperty TCommandProperty = DependencyProperty.Register("TCommand", typeof(ICommand), typeof(TButton));
public static readonly DependencyProperty TCommandTargetProperty = DependencyProperty.Register("TCommandTarget", typeof(object), typeof(TButton));
public ICommand TCommand
{
get
{
return (ICommand)GetValue(TCommandProperty);
}
set
{
SetValue(TCommandProperty, value);
}
}
public object TCommandParameter
{
get
{
return GetValue(TCommandParameterProperty);
}
set
{
SetValue(TCommandParameterProperty, value);
}
}
public IInputElement TCommandTarget
{
get
{
return (IInputElement)GetValue(TCommandTargetProperty);
}
set
{
SetValue(TCommandTargetProperty, value);
}
}
protected override void OnMouseRightButtonUp(MouseButtonEventArgs e)
{
base.OnMouseRightButtonUp(e);
RoutedCommand rcmd = TCommand as RoutedCommand;
if(rcmd!=null)
{
if(rcmd.CanExecute(TCommandParameter,TCommandTarget))
{
rcmd.Execute(TCommandParameter, TCommandTarget);
}
}
else
{
if(TCommand!=null)
{
if(TCommand.CanExecute(TCommandParameter))
{
TCommand.Execute(TCommandParameter);
}
}
}
}
}
再寫一個命令
public class TCommand : ICommand
{
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
Window win = parameter as Window;
if (win != null)
win.Close();
}
}
再界面里綁定:
<local:TButton x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="411,277,0,0" VerticalAlignment="Top" Width="75" TCommand="{Binding TCommand}" TCommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}"/>
本文版權歸腿腿教學網及原創(chuàng)作者所有,未經授權,謝絕轉載。