简体   繁体   中英

WPF Datatemplate Click Command

Many articles let the DataTemplate item which is inside the DataTemplate have a Command , but I don't want to do so.

I want to add a Click Command to the DataTemplate itself, not to the Item inside the DataTemplate . Like when I click the DataTemplate anywhere it should fire the Command , can any body teach me?

Thanks!

If I understand your question correctly, you can use an EventTrigger in combination with InvokeCommandAction like in the following code:

First, add this namespace definition:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

and then in your DataTemplate definition:

<DataTemplate>
    <Label Content="{Binding}">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="MouseDown">
                <i:InvokeCommandAction Command="{Binding Path=DataContext.YourClickCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type YourControl}}}" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </Label>
</DataTemplate>

For above code to work you need to add the System.Windows.Interactivity assembly to your project by going to Add Reference > Assemblies > Extensions .

EDIT: I believe I now understand your question correctly. When you say you want to add the Command

on datatemplate, and I don't want to add command inside datatemplate item

you mean you want to write your code like <DataTemplate Command="{...}"> or <DataTemplate Click="..."> .

On the one hand that is not possible because DataTemplate does not derive from DependencyObject , and on the other hand that is not even necessary.

If you want the MouseDown event to fire when the ListBoxItem is clicked, no matter what part of its template is clicked, you can wrap the DataTemplate s template in a Grid (or StackPanel or any other container) and apply the Interaction.Triggers to that container:

<DataTemplate>
    <Grid Background="Transparent">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="MouseDown">
                <i:InvokeCommandAction Command="{Binding Path=DataContext.YourClickCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type YourControl}}}" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
        <Label Content="{...}" />
        <Label Content="{...}" />
        <Label Content="{...}" /> 
    </Grid>
</DataTemplate>

Now regardless of what label you clicked, the MouseDown event will always fire (note that for this to work you need to give the container a background, else the hit test does not work ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM