我在wpf应用程序中创建了一个用户控件。我是这样用的:
<Page x:Class="InstallerToolkit.Pages.PageVideosNvr"
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"
xmlns:my="clr-namespace:MyProject.UserControls"
mc:Ignorable="d"
d:DesignHeight="525" d:DesignWidth="1050"
Title="PageVideos">
<Grid>
<my:UserControlVideoPlayer Name="VideoPlayer" Margin="559,74,35,155">
</my:UserControlVideoPlayer>
</Grid>
现在,在我的C#页面中,我想访问它,但当我在C#页面后面的代码中键入VideoPlayer对象的名称时,它不会出现。
当我想设置它的一个属性时,我该怎么访问它呢。
将x:Name
而不是Name
提供给UserControl
<my:UserControlVideoPlayer x:Name="VideoPlayer" Margin="559,74,35,155">
现在可以使用this.VideoPlayer
在代码隐藏中访问它。
我建议在引用XAML中的元素时始终使用x:Name
,这是一条经验法则。
关于Name和x:Name之间的区别,请参阅此。