如果 xaml 和后面的代码都属于同一个类,那么只需在名称前加上 x: 前缀,其中 x: 指的是 xaml 名称空间,通常在 Window 标记中,如 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
例如
<Image x:Name="UserimgRock" Source="Rock.png" HorizontalAlignment="Left" Height="100" Margin="277" VerticalAlignment="Top" Width="100" Visibility="Hidden"/>
如果它们不在同一个类中,那么您可能无法使用事件处理程序来访问其他类中的对象,因为对象是各自类的私有对象。
编辑
查看您的代码后,我发现了一些事情,包括您无法访问图像的原因
第一件事,why you cannot access the image object?
原因是,您在控件模板中定义了图像,这将对象的范围限制在模板本身,因此它们无法在外部访问
how to fix?
您可以在后面的代码中定义您需要访问的属性,并将它们绑定到xaml中的相应属性
例如
在用户控件中定义一个依赖属性 UserImgRockVisibility
public Visibility UserImgRockVisibility
{
get { return (Visibility)GetValue(UserImgRockVisibilityProperty); }
set { SetValue(UserImgRockVisibilityProperty, value); }
}
// Using a DependencyProperty as the backing store for UserImgRockVisibility. This enables animation, styling, binding, etc...
public static readonly DependencyProperty UserImgRockVisibilityProperty =
DependencyProperty.Register("UserImgRockVisibility", typeof(Visibility), typeof(UserControl1), new PropertyMetadata(Visibility.Hidden));
在构造函数中将数据上下文设置为自身
DataContext = this;
或在 xaml 中通过绑定到自身
<UserControl x:Class="RockPaper.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"...
DataContext="{Binding RelativeSource={RelativeSource Self}}">
然后使用这个属性来操纵可见性
UserImgRockVisibility = Visibility.Visible;
最终将此属性绑定到 xaml 中图像的可见性
<Image x:Name="userimgRock" Visibility="{Binding UserImgRockVisibility}" ... />
如果你真的不需要名字,则不需要它
这是您在控制模板或数据模板中控制对象属性所需的全部内容
另一种方法
因为我没有发现在用户控件中使用样式和控件模板的意义
您可以通过简单地删除样式和控件模板元素并将这些元素带到用户控件中来实现
通过这样做,您可能不需要额外的属性,您可以简单地访问对象,因为它们将在类范围内
我可以看到你已经使用它们来检测鼠标悬停,你可以直接使用 MouseEnter、MouseLeave 等事件在元素中使用事件触发器
例如,
<UserControl x:Class="RockPaper.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<Button x:Name="btnRock" Opacity=".3" HorizontalAlignment="Left" Margin="44,82.418,0,0" VerticalAlignment="Top" Width="100" Height="100" Click="btnRock_Click">
<StackPanel>
<Image />
</StackPanel>
</Button>
<Image x:Name="userimgRock" Visibility="Hidden" HorizontalAlignment="Left" Height="100" Margin="277.164,228.418,0,0" VerticalAlignment="Top" Width="100" Opacity="1" />
</Grid>
<UserControl.Triggers>
<EventTrigger SourceName="btnRock" RoutedEvent="MouseEnter" >
<BeginStoryboard>
<Storyboard>
<DoubleAnimation x:Name="enter" To="1" Storyboard.TargetName="btnRock" Storyboard.TargetProperty="Opacity"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
<EventTrigger SourceName="btnRock" RoutedEvent="MouseLeave" >
<BeginStoryboard>
<Storyboard>
<DoubleAnimation To=".3" Storyboard.TargetName="btnRock" Storyboard.TargetProperty="Opacity"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</UserControl.Triggers>
</UserControl>
请注意,我删除了一些不必要的额外代码,例如
然后正常使用图片对象作为
userimgRock.Visibility = Visibility.Visible;
现在您可以选择自己喜欢的。两者都试一下,看看什么对你来说方便。