如何在模板按钮中触发Click-Event

时间:2017-05-13 10:06:15

标签: c# wpf command custom-controls

我搜索过这个问题,但没有找到任何解决方案。

我在Button.Template中有一个带有图像的模板按钮。此按钮是CustomControl的一部分。

<Button x:Name="PART_DELETESEARCHBUTTON"
        Style="{StaticResource CustomDeleteButtonStyle}"
        Command="{x:Static local:CustomSearchControl.DeleteCommand}"
        Width="20" Height="20"
        Margin="0,0,5,0">
  <Button.Template>
      <ControlTemplate>
          <Image x:Name="PART_IMGDELETE" 
                 Source="{DynamicResource _Av_PinClose_Dark}"
                 Cursor="Hand"
                 Margin="2"/>
          <ControlTemplate.Triggers>
              <Trigger Property="IsMouseOver" Value="True">
                  <Setter Property="Background" Value="Red"/>
              </Trigger>
          </ControlTemplate.Triggers>
      </ControlTemplate>
  </Button.Template>
          

在CustomControl的Class中,实现了Button的命令:

static CustomSearchControl()
{
    DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomSearchControl),
        new FrameworkPropertyMetadata(typeof(CustomSearchControl)));

    CommandManager.RegisterClassCommandBinding(typeof(CustomSearchControl),
                new CommandBinding(CustomSearchControl.DeleteCommand, C_DeleteCommand));
}

public override void OnApplyTemplate()
{
    base.OnApplyTemplate();
}

static void C_DeleteCommand(object sender, ExecutedRoutedEventArgs e)
{
    CustomSearchControl mycontrol = sender as CustomSearchControl;
    mycontrol.SearchText = "";
}
public static readonly ICommand DeleteCommand = new RoutedUICommand("DeleteCommand", "DeleteCommand",
                                    typeof(CustomSearchControl),
                                            new InputGestureCollection(new InputGesture[] { new KeyGesture(Key.Enter), new MouseGesture(MouseAction.LeftClick) }));

现在,如果MouseClick on Button(Image),则不会触发Command。使用Image删除Button.Template时,一切正常。

如何将Templated.ButtonImage上的MouseClick绑定到Command?

或者还有其他解决方法吗?

其次:DeleteCommand清除此CustomControl中的TextBox。这很有效,但在Clearing之后,TextBox失去了Focus。单击按钮后,TextBox再次获取焦点怎么办?触发左右???

1 个答案:

答案 0 :(得分:0)

我无法使用未执行的命令重新创建问题。它对我来说很好。

对于焦点问题,按钮在单击时会获得焦点。您必须将焦点显式设置回文本框。这很简单。如果模板中没有名称,请给它一个;我称之为“PART_SearchTextBox”,但您可以替换自己的名字。

public override void OnApplyTemplate()
{
    base.OnApplyTemplate();

    _PART_SearchTextBox = (TextBox)GetTemplateChild("PART_SearchTextBox");
}

public void ClearSearchText()
{
    SearchText = "";
    _PART_SearchTextBox.Focus();
}

private TextBox _PART_SearchTextBox;

static void C_DeleteCommand(object sender, ExecutedRoutedEventArgs e)
{
    CustomSearchControl mycontrol = sender as CustomSearchControl;
    mycontrol.ClearSearchText();
}

在CustomSearchControl模板中,将文本框命名为PART_SearchTextBox

<TextBox 
    x:Name="PART_SearchTextBox"
    Text="{Binding SearchText, RelativeSource={RelativeSource TemplatedParent}}"
    ...etc...
    />