我是使用WPF表单的新手,我创建了一个显示来自数据库的图像的页面,但是尽管经过几天的搜索,我找不到一种方法可以知道哪个图像有鼠标悬停或鼠标点击事件它
设置我的图像:
public class RBimageData
{
private string _Title;
public string Title
{
get { return this._Title; }
set { this._Title = value; }
}
private BitmapImage _ImageData;
public BitmapImage ImageData
{
get { return this._ImageData; }
set { this._ImageData = value; }
}
private String _ImageID;
public String ImageID
{
get { return this._ImageID; }
set { this._ImageID = value; }
}
}
public MainWindow()
{
InitializeComponent();
RBpartsList rbPartsList = mongoDB.GetRBparts("elements", 1, 7); // get parts from database
List<RBpartsImages> rbImages = rbPartsList.RBparts;
List<RBimageData> md = new List<RBimageData>();
foreach (RBpartsImages img in rbImages)
{
RBimageData m = new RBimageData
{
Title = img.ImageFilename,
ImageID = "id_"+img.PartNum,
ImageData = LoadImage(rbPartsList.FilePath,img.ImageFilename) }; // provides BitmapImage URI for image
md.Add(m);
}
RBbox.ItemsSource = md.ToArray();
} 并且图像显示在XAML中,我使用Tag元素来保存ImageID:
<ListView x:Name="RBbox" HorizontalAlignment="Stretch" VerticalAlignment="Bottom" Height="143" Margin="10,0,10,10" Background="#FFE6E2E2">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="7" Rows="1" HorizontalAlignment="Stretch"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<Border BorderThickness="1" BorderBrush="#FF000000" VerticalAlignment="Top" HorizontalAlignment="Left" Width="100" Height="100" Background="#FFC1A0A0">
<Button
MouseEnter="IdentifyPartImage_MouseEnter"
MouseLeave="IdentifyPartImage_MouseLeave" >
<Image Source="{Binding ImageData}"
HorizontalAlignment="Stretch" VerticalAlignment="Top"
Stretch="UniformToFill"
Tag="{Binding ImageID}"/>
</Button>
</Border>
<TextBlock Text="{Binding Title}" HorizontalAlignment="Center" VerticalAlignment="Top" Width="100" Height="14" FontSize="10" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
但在我的代码中,this.Tag始终为null:
private void IdentifyPartImage_MouseEnter(object sender, MouseEventArgs e)
{
// this fails - tag is null
var imgId = this.Tag.ToString();
Debug.WriteLine("id: {0}, {1}", "imageID", imgId.ToString());
}
它不能使用x:Name =&#34; {Binding ImageID}&#34; ..我找不到任何可以让我识别哪个图片被点击的内容,你能不能救命?
感谢。
答案 0 :(得分:1)
在代码隐藏中引用this
时,它指向Window对象。您正在寻找Tag
控件的Image
属性。
为此,我建议在MouseEnter="IdentifyPartImage_MouseEnter"
控件上定义MouseLeave="IdentifyPartImage_MouseLeave"
和Image
事件,然后sender
参数将是Image
对象。< / p>
在您的XAML中:
<Button>
<Image Source="{Binding ImageData}"
HorizontalAlignment="Stretch"
VerticalAlignment="Top"
Stretch="UniformToFill"
Tag="{Binding ImageID}"
MouseEnter="IdentifyPartImage_MouseEnter"
MouseLeave="IdentifyPartImage_MouseLeave"/>
</Button>
在您的代码隐藏中:
private void IdentifyPartImage_MouseEnter(object sender, MouseEventArgs e)
{
var imgId = ((Image)sender).Tag.ToString();
Debug.WriteLine("id: {0}, {1}", "imageID", imgId);
}