2009-12-11 157 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

相關問題