【问题标题】:Access a parent from within an event method从事件方法中访问父级
【发布时间】:2012-02-23 17:05:36
【问题描述】:

我正在尝试向 .net 4.0 DatePicker 日历中添加一个按钮,并且我有该按钮,但不知道如何授予它访问日历的权限。我正在使用的指南是通过在 _Click 方法中使用 this 引用来完成的,但是当我这样做时,“this”指的是按钮而不是日历。所以我的想法是使用 GetParent 然后 GetChild 来获取对日历的引用。但是 GetParent 对我来说是不可用的。有什么想法吗?

谢谢

<Style x:Key="DatePickerCalendarStyle" TargetType="{x:Type Calendar}" BasedOn="{StaticResource {x:Type Calendar}}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Calendar}">
                    <Border BorderThickness="{TemplateBinding BorderThickness}"
                            Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}">
                        <StackPanel Orientation="Vertical">
                            <StackPanel x:Name="PART_Root" HorizontalAlignment="Center">
                                <CalendarItem x:Name="PART_CalendarItem"
                                              BorderBrush="{TemplateBinding BorderBrush}"
                                              BorderThickness="{TemplateBinding BorderThickness}"
                                              Background="{TemplateBinding Background}"
                                              Style="{TemplateBinding CalendarItemStyle}" />
                                <Button x:Name="PART_TodayButton"
                                        HorizontalAlignment="Center"
                                        VerticalAlignment="Center"
                                        Margin="10,0,10,2"
                                        Content="Today"
                                        Click="PART_TodayButton_Click"/>

【问题讨论】:

    标签: c# wpf calendar datepicker parent-child


    【解决方案1】:

    看看VisualTreeHelper Class,特别是GetParent方法

    由于日历是按钮的父级,因此您无需在树中向上然后再次向下,因此不应使用GetChild

    【讨论】:

    • 日历是父级?我以为堆栈面板是,这让它变得容易多了:)
    • 对不起,让我改写一下日历是按钮的祖先。所以你会循环调用VisualTreeHelper.GetParent,直到你得到日历
    【解决方案2】:

    在您的点击处理程序的参数中,您有“发件人”(对象):这是来自您要使用 VisualTreeHelper 类查找父级的发件人。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多