2009-12-11 165 views
0

我有一个非常简单的app.xaml.cs,当应用程序启动时,创建一个新的PrimeWindow,并使其可以访问到外部。有没有方法通过名称引用WPF UI元素的子元素?

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中的,通过类似

DockPanel x = App.AppPrimeWindow.dockPanel1; 

但挖得更深似乎并不容易做到。我可以得到DockPanel的子项的UIElementCollection,并且我可以通过整数索引获得单个子项,但从可维护性的角度来看,显然不是这样做的方法。

回答

1

如果您需要引用孩子,则通过UIElementCollection可以做到这一点。如果你只是想访问MyContentArea,没有什么从做以下阻止你:

MyControls.ContentArea = App.AppPrimeWindow.myContentArea; 

如果您需要动态地看,如果那里有你的DockPanel中内的含量 - 面积,下面的工作:

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 
    } 
} 
+0

所有的答案都有很好的出于不同的原因;然而,这一点突出了最简单的方法来做到这一点,并在同一时间向我解释了别的东西。所以:接受。 – Beska 2009-12-11 22:12:22

1
... 
<DockPanel Name="dockPanel1" x:FieldModifier="Public" VerticalAlignment="Top"> 
... 

这将使dockPanel1业界人士,所以这将是访问从其他类

注意它,因为它打破了封装的不是很好的做法......你也可以暴露DockPanel作为公众在您的代码中定义的属性

+0

谢谢!现在我只需要弄清楚我是否真的想在这里打破封装,或者是否有更好的方法来做我想做的事情(可能是。) – Beska 2009-12-11 22:13:41

4

很简单,

ContentArea contentArea = dockpanel1.FindName("MyContentArea") as ContentArea; 
+0

这实际上就是我正在尝试的,并且认为我必须这么做,但是没有意识到FindName是我正在寻找的......谢谢! – Beska 2009-12-11 22:13:01

相关问题