代码之家  ›  专栏  ›  技术社区  ›  Beska

是否有方法按名称引用wpf ui元素的子元素?

  •  0
  • Beska  · 技术社区  · 15 年前

    我有一个非常简单的app.xaml.cs,当应用程序启动时,它会创建一个新的PrimeWindow,并使它可以从外部访问。

    public partial class App : Application
    {
        public static PrimeWindow AppPrimeWindow { get; set; }
    
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            AppPrimeWindow = new PrimeWindow();
            AppPrimeWindow.Show();    
        }
    }
    

    PrimeWindow的XAML如下所示:

    <Window x:Class="WpfApplication1.PrimeWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="500" Width="500"
        xmlns:MyControls="clr-namespace:WpfApplication1">
        <DockPanel Name="dockPanel1" VerticalAlignment="Top">
            <MyControls:ContentArea x:Name="MyContentArea" />
        </DockPanel>
    </Window>
    

    作为一个完全的WPF新手,我无疑会把一些事情搞砸,但现在的问题是: 如何在其他地方的代码中引用内容区域? 我可以很容易地通过

    DockPanel x = App.AppPrimeWindow.dockPanel1;
    

    但再深入挖掘似乎不容易。我可以得到DockPanel子项的uielementCollection,我可以通过一个整数索引获得单个子项,但是从可维护性的角度来看,这显然不是实现这一点的方法。

    3 回复  |  直到 15 年前
        1
  •  1
  •   Will Eddins ianpoley    15 年前

    如果你需要参考孩子们,通过 UIElementCollection 到处都可以。如果您只想访问MyContentarea,没有什么可以阻止您执行以下操作:

    MyControls.ContentArea = App.AppPrimeWindow.myContentArea;
    

    如果需要动态查看DockPanel中是否存在ContentArea,则可以使用以下方法:

    DockPanel dock = App.AppPrimeWindow.dockPanel1;
    
    for (int i = 0; i < dock.Children.Count; i++)
    {
      if (dock.Children[i] is ContentArea) // Checking the type
      {
        ContentArea ca = (ContentArea)dock.Children[i];
        // logic here
        // return;/break; if you're only processing a single ContentArea
      }
    }
    
        2
  •  4
  •   mattdlong    15 年前

    很简单,

    ContentArea contentArea = dockpanel1.FindName("MyContentArea") as ContentArea;
    
        3
  •  1
  •   Thomas Levesque    15 年前
    ...
    <DockPanel Name="dockPanel1" x:FieldModifier="Public" VerticalAlignment="Top">
    ...
    

    这将使 dockPanel1 字段公用,因此可以从其他类访问它

    注意,这不是很好的做法,因为它破坏了封装…你也可以暴露 DockPanel 作为您的代码隐藏中定义的公共属性