Is there a way to reference the child of a WPF UI element by name?
I've got a very simple app.xaml.cs that, when the app starts up, creates a new PrimeWindow, and makes it accessible to the outside.开发者_开发问答
public partial class App : Application
{
public static PrimeWindow AppPrimeWindow { get; set; }
private void Application_Startup(object sender, StartupEventArgs e)
{
AppPrimeWindow = new PrimeWindow();
AppPrimeWindow.Show();
}
}
The xaml for PrimeWindow looks like this:
<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>
Being a complete WPF novice, I'm doubtless messing several things up, but the question of the moment is this: how do I reference the content area in code elsewhere? I can easily get ahold of the DockPanel, via something like
DockPanel x = App.AppPrimeWindow.dockPanel1;
But digging any deeper doesn't seem easy to do. I can get a UIElementCollection of the DockPanel's children, and I can get individual children by an integer index, but, from a maintainability standpoint, that's clearly not the way to do this.
Very simply,
ContentArea contentArea = dockpanel1.FindName("MyContentArea") as ContentArea;
If you need to reference the children, passing the UIElementCollection
around would do it. If you just wanted to access MyContentArea, there's nothing stopping you from doing the following:
MyControls.ContentArea = App.AppPrimeWindow.myContentArea;
If you need to dynamically see if theres a ContentArea within your DockPanel, the following would work:
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
}
}
...
<DockPanel Name="dockPanel1" x:FieldModifier="Public" VerticalAlignment="Top">
...
This will make the dockPanel1
field public, so it will be accessible from other classes
Note that it's not very good practice as it breaks encapsulation... You could also expose the DockPanel
as a public property defined in your code-behind
精彩评论