【发布时间】:2014-05-01 17:06:43
【问题描述】:
我有一个 xaml 文件,里面有 UserControl,还会加载另一个 xaml 文件。
<UserControl mc:Ignorable="d" d:Title="MainWindow"
x:Class="TouchControls.Pages.NoticesView.Libov"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:local="clr-namespace:TouchControls.Pages.NoticesView"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008">
<Grid Background="White" Name="LibovLoad" Width="635" Height="400" HorizontalAlignment="Left" VerticalAlignment="Top">
<!-- here the other xaml file content will dynamically be appended -->
</Grid>
另一个 xaml 文件也是一个 UserControl:
<UserControl mc:Ignorable="d" d:Title="MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008">
<Grid Margin="20">
<Slider Height="60" HorizontalAlignment="Right" Margin="20, 0" Maximum="0.3" Minimum="0.2" Orientation="Vertical" Panel.ZIndex="5" Value="0.23" x:Name="ScaleSlider" />
<Canvas Name="LibovPhoto" Margin="30, 10">
<Canvas Name="LibovCanvas"></Canvas>
</Canvas>
</Grid>
</UserControl>
这就是加载extern xaml文件的方法:
StringReader stringReader = new StringReader(LoadXAMLFile());
XmlReader xmlReader = new XmlTextReader(stringReader);
LibovLoad.Children.Clear();
LibovLoad.Children.Add((UIElement)XamlReader.Load(xmlReader));
现在我想访问这个嵌套的 UserControl 中的一个元素 - 名为 LibovPhoto 的画布元素。但我不知道,我怎么能做到这一点。如果我尝试 FindName 方法,则返回值为 null(但 xaml 文件加载正确!)直到我来的 UserControl 节点,但不是更远。我不知道如何获得 UserControl 元素的子元素。 有谁能够帮我?谢谢!
【问题讨论】:
-
通常在您的用户控件中,您会创建一些与用户控件中的控件交互的依赖属性。但我不确定您将如何在动态 xaml 中定义它们。
-
我觉得这个小方法可以解决你的问题:link
标签: c# wpf xaml user-controls nested