首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从ControlTemplate获取对象

从ControlTemplate获取对象
EN

Stack Overflow用户
提问于 2013-12-28 23:27:56
回答 2查看 429关注 0票数 0

我有资源字典

代码语言:javascript
复制
<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中从应用的ControlTemplate实例化“菜单”对象?我可以在空中获取Ellipse对象,但我需要菜单对象。

代码语言:javascript
复制
public partial class PanelMnuClass
{
    private void OnMouseDown(object obj, MouseButtonEventArgs args)
    {
        MessageBox.Show("Panel clicked!");
    }


}
EN

回答 2

Stack Overflow用户

发布于 2013-12-29 02:17:17

你可以通过访问Ellipse的TemplatedParent来获取菜单对象,如下所示:

代码语言:javascript
复制
private void OnMouseDown(object obj, MouseButtonEventArgs args)
{
   Menu menu = ((Ellipse)obj).TemplatedParent as Menu;
}
票数 0
EN

Stack Overflow用户

发布于 2013-12-29 02:24:03

尝试一下,找到菜单类型的第一个元素。

代码语言:javascript
复制
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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20816183

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档