我在DataTemplate中有一个按钮,该按钮绑定到我的ViewModel中的命令。该按钮还具有一个eventtrigger,可以启动一个故事板,该故事板隐藏了编辑控件(其中该按钮是一部分。)

如果我拿起预览事件,故事板正常工作,但是该命令从未被调用。如果我在EventTrigger中拿起Mousedown事件,则该命令可以正常工作,但故事板没有执行。

单击按钮时,如何获得命令和情节提要进行执行?

<Button Content="Save" Command="{Binding SaveCommand}" >
    <Button.Triggers>
        <EventTrigger RoutedEvent="Button.PreviewMouseDown">
            <EventTrigger.Actions>
                <BeginStoryboard Storyboard="{DynamicResource sbCloseTitleEdit}"/>
            </EventTrigger.Actions>
        </EventTrigger>
    </Button.Triggers>
</Button>
有帮助吗?

解决方案

我最终通过为包含DataTemplate的ResousceDictionary添加一个代码文件来解决我的问题。我不知道这是可能的,但发现了这种解释:

是否可以在WPF中的资源词典后面设置代码进行事件处理?

而不是使用EventTrigger开始隐藏编辑控件的故事板,而是在代码范围内添加了一个点击处理程序。这有点gludgy,因为我必须找到相对于单击的按钮的面板,因为这是唯一可用的参考,但可以使用。

如果有人有一个问题,仍在寻找更好的解决方案。

其他提示

IVE尝试了您的代码,我发现它可以与事件触发器一起使用 PreviewMouseDown, ,仅首先执行命令,然后动画发射。

这是我的资源

<Storyboard x:Key="sbCloseTitleEdit">
  <ColorAnimation Storyboard.TargetProperty="(Rectangle.Fill).Color" 
                  To="Blue" Duration="0:0:3" Storyboard.TargetName="rect" >
  </ColorAnimation>
</Storyboard>

我的xaml

<Grid>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="Auto" />
    <ColumnDefinition Width="Auto" />
  </Grid.ColumnDefinitions>
  <Grid.RowDefinitions>
    <RowDefinition Height="Auto" />
  </Grid.RowDefinitions>
  <Button Content="Save" Command="{Binding SaveCommand}" >
    <Button.Triggers>
      <EventTrigger RoutedEvent="Button.PreviewMouseDown">
        <EventTrigger.Actions>
          <BeginStoryboard 
            Storyboard="{StaticResource sbCloseTitleEdit}"/>
        </EventTrigger.Actions>
      </EventTrigger>
    </Button.Triggers>
  </Button>
  <Rectangle Name="rect" Width="30" Height="30" 
             Grid.Column="1" Fill="Red" />
</Grid>

和我的观点模型

public class MainViewModel
{
    public ActionCommand SaveCommand { get; private set; }
    public MainViewModel()
    {
        SaveCommand = new ActionCommand();
    }
}

public class ActionCommand : ICommand
{
    public void Execute(object parameter)
    {
        // gets fired if event trigger is preview mode
    }

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public event EventHandler CanExecuteChanged;
}

您确定您还没有错过什么吗?

我通过在EventTrigger中调用命令以及您要触发的其他操作来实现这一目标:

<Button Command="{Binding AcceptCommand}" Content="Accept">
  <i:Interaction.Triggers>
    <i:EventTrigger EventName="Click">
      <i:InvokeCommandAction Command="{Binding AcceptCommand}"/>
      <triggers:UpdatePropertyAction TargetObject="{Binding RelativeSource={RelativeSource AncestorType={x:Type Controls:ChildWindow}, Mode=FindAncestor}}" TargetProperty="DialogResult" Value="True"  />
    </i:EventTrigger>
  </i:Interaction.Triggers>
</Button>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top