我想在特定查询操作中添加一个clickable事件
示例:我有这3个列表Image
当我单击该列表之一时如何添加操作,它会转到我选择并执行某操作的ID
Mydb示例Database
查询
select * from library where id_movie = (the one that i clicked)
Xaml
<ItemsControl ItemsSource="{Binding Path=Library}" Margin="0,0,2,0">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="viewModels:Card">
<UniformGrid Rows="1" Columns="1">
<StackPanel Orientation="Horizontal" Width="100" Height="150" Margin="10,25,0,0" >
<Image Width="100" Source="{Binding Path=cover}"/>
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Margin="10,0,0,0">
<Label Content="{Binding Path=title}"/>
</StackPanel>
</UniformGrid>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
MyClass
public class VModel
{
public VModel()
{
DataTable dt = new DataTable();
DataSet ds = new DataSet();
using (MySqlConnection connection = new MySqlConnection("SERVER=localhost;" + "DATABASE=library;" + "UID=root;" + "PASSWORD=;"))
{
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = new MySqlCommand("Select * from movie_list", connection);
adapter.Fill(dt);
}
Library = dt.DefaultView;
}
public DataView Library { get; private set; }
}
答案 0 :(得分:1)
我认为这就是您要寻找的。每个项目都是一个按钮,其中包含图像和标签。单击按钮将调用带有参数的命令(在窗口的DataContext上)。
<ItemsControl.ItemTemplate>
<DataTemplate DataType="viewModels:Card">
<Button Command="{Binding DataContext.QueryCommand, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}"
CommandParameter="{Binding Path=id}">
<StackPanel>
<Image Width="100" Source="{Binding Path=cover}"/>
<Label Content="{Binding Path=title}" HorizontalContentAlignment="Center"/>
<StackPanel>
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
答案 1 :(得分:0)
将Image控件更改为以下代码,它将是Image的按钮。 看到Command绑定到全局DataContext,因为在viewmodel中我将声明command。我使用命令参数并在其中传递ID。
<Button Command="{Binding Path=DataContext.DoSomething, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}" CommandParameter="{Binding id}">
<StackPanel>
<Image Width="100" Source="{Binding Path=cover}"/>
</StackPanel>
</Button>
然后您需要在ViewModel中声明Command
public ICommand DoSomething {get;set;}
并在构造函数中对其进行初始化
DoSomething = new DoSomethingCommand(this);
为定义fo命令添加另一个类
internal class DoSomethingCommand: ICommand
{
private VModel vm;
public PlotPlane(VModel mainViewModel)
{
this.vm = mainViewModel;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
var id = (id)parameter;
//do something, use vm to access your viewmodel
}
}