我有一個非常簡單的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,並且我可以通過整數索引獲得單個子項,但從可維護性的角度來看,顯然不是這樣做的方法。
所有的答案都有很好的出於不同的原因;然而,這一點突出了最簡單的方法來做到這一點,並在同一時間向我解釋了別的東西。所以:接受。 – Beska 2009-12-11 22:12:22