【问题标题】:How to access a WPF control located in a ControlTemplate?如何访问位于 ControlTemplate 中的 WPF 控件?
【发布时间】:2010-10-23 15:23:53
【问题描述】:

通常,WPF 控件是在 .xaml 文件中声明的,而不是在后面的代码(.xaml.cs 文件)中声明的。但是,有时我需要在后面的代码中使用其中一些控件来操作它们。如果它“驻留在”xaml 文件中,我如何获取此类控件的句柄?

【问题讨论】:

    标签: wpf controls controltemplate


    【解决方案1】:

    您可以使用 ControlTemplate 类的 FindName() 方法。

    // Finding the grid that is generated by the ControlTemplate of the Button
    Grid gridInTemplate = (Grid)myButton1.Template.FindName("grid", myButton1);
    

    【讨论】:

    • 这为我返回了一个空异常,然后我在 SO 上尝试一些不同的答案时意识到了一些事情:如果您正在查看的模板 应用于 myButton1,请使用 CSharper 的答案我>。但如果 myButton1 只是上述模板的成员,请改用 (Grid)myButton1.FindName("grid");(在按钮处理程序中很有用)。
    【解决方案2】:

    我不确定你在问什么,所以我会尝试回答我解释为你的问题的两个实例。

    1) 如果你想声明一个显式控件,然后直接编辑它,你所要做的就是像这样设置 name 属性:

    <Canvas x:Name="myCanvas"/>
    

    然后您可以通过名称访问画布,如下所示:

    myCanvas.Background = Brushes.Blue;
    

    2) 如果您要声明一个通用控件,然后多次使用它,您可以这样做:

    <Window>
       <Window.Resources>
          <Ellipse x:Key="myEllipse" Height="10" Width="10">
       </Window.Resources>
    </Window>
    

    然后您可以在代码中使用以下语法访问该预定义控件:

    Ellipse tempEllipse = (Ellipse)FindResource("MyEllipse");
    

    如果您想将资源用作多个控件的模板,请添加 x:Shared="false"。

    【讨论】:

    • FindName() 一直返回 null。 FindResource() 为我的应用程序工作。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-07
    • 1970-01-01
    • 1970-01-01
    • 2010-12-06
    • 1970-01-01
    相关资源
    最近更新 更多