如何在ControlTemplate中获取父事件?

时间:2015-02-12 13:17:57

标签: c# wpf

我想从单选按钮ControlTemplate中的视图模型中调用命令。并在事件Checked被提出时执行此操作

我试过了:

<ControlTemplate x:Key="RequestTypeControlTemplate" TargetType="RadioButton">
    <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="0,0,0,2">
        <ContentPresenter Margin="10,0,10,0">
            <i:Interaction.Triggers>
                <!-- Checked event from parent -->
                <i:EventTrigger EventName="Checked">
                    <!-- Command from view model and binding to tag of radio button as arg -->
                    <i:InvokeCommandAction Command="{Binding DataContext.OnTypeChangedCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" CommandParameter="{Binding Tag, RelativeSource={RelativeSource TemplatedParent}}" />
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </ContentPresenter>
    </Border>
</ControlTemplate>

但我认为事件来自ContentPresenter,而不是来自RadioButton。我如何从RadioButton获得活动?

编辑:

 <RadioButton Content="All requests"
                                 ContentTemplate="{StaticResource RadioButtonDataTemplate}"
                                 GroupName="Filter"
                                 IsChecked="True"
                                 Style="{StaticResource RadioButtonStyle}"
                                 Template="{StaticResource RequestTypeControlTemplate}"
                                 Tag="{x:Static local:ContentType.Any}"/>

在viewModel

  public ICommand OnTypeChangedCommand
    {
        get
        {
            return m_TypeChangedCommand ?? (m_TypeChangedCommand = new DelegateCommand<ContentType>(OnTypeChanged));
        }
    }

    public void OnTypeChanged(ContentType type)
    {
        Debug.WriteLine(type);
    }

1 个答案:

答案 0 :(得分:0)

你不能这样做,因为路由事件只是从元素(气泡)或元素(隧道)处理

您可以使用的是IsChecked属性上的DataTrigger。

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

<i:Interaction.Triggers>
    <ei:DataTrigger Binding="{Binding IsChecked,RelativeSource={RelativeSource AncestorType=RadioButton}}" Value=True>
         <i:InvokeCommandAction Command="{Binding DataContext.OnTypeChangedCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" CommandParameter="{Binding Tag, RelativeSource={RelativeSource AncestorType=RadioButton}}}" />       
    </ei:DataTrigger>
</i:Interaction.Triggers>