从ControlTemplate获取对象

时间:2013-12-28 15:27:56

标签: wpf events controltemplate

我有资源字典

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:PieMenuSample="clr-namespace:PieMenuSample" 
xmlns:Microsoft_Windows_Themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Luna"
x:Class="PieMenuSample.PanelMnuClass">
<Style x:Key="RadialMenuStyle" TargetType="{x:Type Menu}">
    <Setter Property="ItemsPanel" Value="{DynamicResource RadialItemsPanelTemplate}" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Menu}">

                <Grid Width="Auto" Height="Auto" RenderTransformOrigin="0.5,0.5">
                    <ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                    <Ellipse HorizontalAlignment="Center" VerticalAlignment="Center" Width="40" Height="40" StrokeThickness="4" Fill="#FF6D8593" MouseDown="OnMouseDown"  >

                        <Ellipse.Stroke>
                            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                                <GradientStop Color="#FF000000" Offset="0"/>
                                <GradientStop Color="#FF6D8593" Offset="1"/>
                            </LinearGradientBrush>
                        </Ellipse.Stroke>
                    </Ellipse>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
<ItemsPanelTemplate x:Key="RadialItemsPanelTemplate">
    <PieMenuSample:RadialPanel/>
</ItemsPanelTemplate>

如何从OnMouseDown中的Aplied ControlTemplate实例化“Menu”对象? 我可以在虚空中获取Ellipse对象,但我需要Menu对象。

public partial class PanelMnuClass
{
    private void OnMouseDown(object obj, MouseButtonEventArgs args)
    {
        MessageBox.Show("Panel clicked!");
    }


}

2 个答案:

答案 0 :(得分:0)

您可以通过访问Ellipse的TemplatedParent来获取菜单对象:

private void OnMouseDown(object obj, MouseButtonEventArgs args)
{
   Menu menu = ((Ellipse)obj).TemplatedParent as Menu;
}

答案 1 :(得分:0)

试试这个,找到Menu类型的第一个元素。

private void OnMouseDown(object obj, MouseButtonEventArgs args)
{
   Menu menu = FindVisualParent<Menu>((Ellipse)obj);
}

public static T FindVisualParent<T>(UIElement element) where T : UIElement
{
    UIElement parent = element; 
    while (parent != null)
    {
        T correctlyTyped = parent as T;
        if (correctlyTyped != null)
        {
            return correctlyTyped;
        }
        parent = VisualTreeHelper.GetParent(parent) as UIElement;
    } return null;
}