我正在努力解决这个问题,我试图处理PreviewMouseLeftButtonDown& MouseEnter&我绑定的ListBox中的MouseLeave事件。目前正在学习WPF。
图像在我的ListBox中,其他控件在这里是一张图片以供澄清。
我的问题是两个图像控件在代码隐藏中未知,因为它们位于DataTemplate中,这就是为什么我无法处理它们。
继承我的Xaml代码:
<ListBox Name="ListBoxDownload" Height="414" Width="729" Canvas.Left="-3" Visibility="Collapsed">
<ListBox.ItemTemplate>
<DataTemplate>
<Canvas Height="89" >
<Canvas Height="86" Width="11" Background="#FFC33232" Canvas.Left="-2"/>
<ProgressBar Width="694" Canvas.Left="20" Canvas.Top="76" Height="10" Value="{Binding Value, UpdateSourceTrigger=PropertyChanged}" Maximum="{Binding Maximum}" Minimum="0"/>
<Label Foreground="White" FontFamily="/SpotWatch;component/Resources/Fonts/#Montserrat Light" FontSize="18" Content="{Binding Name}" Canvas.Left="14" Canvas.Top="-4"/>
<Label Foreground="#FFC3BDBD" FontFamily="/SpotWatch;component/Resources/Fonts/#Montserrat Ultra Light" FontSize="14" Content="{Binding Artist}" Canvas.Left="14" Canvas.Top="25"/>
<Label Foreground="#FF8D8D8D" FontFamily="/SpotWatch;component/Resources/Fonts/#Montserrat Ultra Light" FontSize="12" Content="{Binding Status}" Canvas.Left="14" Canvas.Top="50"/>
<Image Name="ImageDeleteSong" Source="/Resources/Images/SpotWatch.Delete.png" Canvas.Left="675" Canvas.Top="6" Width="17" Height="19" MouseEnter="ImageDeleteSong_MouseEnter" MouseLeave="ImageDeleteSong_MouseLeave" PreviewMouseLeftButtonDown="ImageDeleteSong_PreviewMouseLeftButtonDown"/>
<Image Name="ImageRemoveSong" Source="/Resources/Images/SpotWatch.Remove.png" Canvas.Left="697" Canvas.Top="6" Width="17" Height="19" MouseEnter="ImageRemoveSong_MouseEnter" MouseLeave="ImageRemoveSong_MouseLeave" PreviewMouseLeftButtonDown="ImageRemoveSong_PreviewMouseLeftButtonDown"/>
</Canvas>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
答案 0 :(得分:0)
在后面的代码中不需要知道图像,如果您将事件连接起来,则将图像控件作为第一个参数传递。你只需要施展它。
或者将图像包装在一个按钮中,绑定Command
并根据需要通过CommandParameter
绑定传递一些内容。 (通常我会避免事件并在视图模型上绑定命令。)
为什么你还需要访问图像?这不是你应该做的事情。如果需要修改它们,则应绑定相应的属性,然后修改绑定数据。
鉴于你在评论中所说的话,我会这样做:
public SomeViewModel()
{
_deleteUser = new DelegateCommand(user =>
Users.Remove((Person)user)
);
}
private readonly ObservableCollection<Person> _Users;
public ObservableCollection<Person> Users { get { return _Users; } }
private readonly DelegateCommand _deleteUser;
public DelegateCommand DeleteUser { get { return _deleteUser; } }
<ItemsControl ItemsSource="{Binding Users}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<!-- Some content here -->
<Button Command="{Binding RelativeSource={RelativeSource AncestorType=ItemsControl},
Path=DataContext.DeleteUser}"
CommandParameter="{Binding}">Remove</Button>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
关键点:
RelativeSource
{Binding}
)作为参数传递。(DelegateCommand
是基于代理的简单ICommand
实现,您可以在网上找到实施示例。)