我创建了一个拥有多个标签的UserControl。另一方面,我有一个窗口(简单网格),它创建6个UserControl实例并将它们放在一行中。在UserControl中捕获鼠标点击
我的问题是:如何在用户点击userControl(它的任何部分)时触发一些动作?
我试着在UserControl cs
文件中添加MouseDown
事件处理程序,并在UserControl实例创建期间在父窗口内部添加事件处理程序,但这不起任何作用。我也试过添加PreviewMouseLeftButtonDown
,MouseEnter
,MouseLeftButtonDownButton
,但没有任何工作。
这是父窗口的一部分:
public BuyerSellerMonitorGridWindow()
{
InitializeComponent();
for (int i = 0; i < 6; i++)
{
// Add new column to grid
this.grdBuyer.ColumnDefinitions.Add(new ColumnDefinition());
// Create and add new transaction
UserControl uc = new UserControl();
uc.PreviewMouseLeftButtonDown += uc_MouseDown;
System.Windows.Controls.Grid.SetRow(uc, 0);
System.Windows.Controls.Grid.SetColumn(uc, i);
this.grdBuyer.Children.Add(uc);
}
}
这是用户控件:
public partial class Transaction: UserControl
{
public Transaction()
{
InitializeComponent();
}
private void TransactionClicked()
{
Console.WriteLine("test");
}
}
这是xaml
:
<UserControl x:Class="AssetStudio.Dialogs.Transaction"
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:local="clr-namespace:AssetStudio.Dialogs"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<StackPanel x:Name="frameTransaction">
<Label x:Name="lblClientName" Content="Client A" Height="35"/>
<Label x:Name="lblDate" Content="2017/05/01"/>
<Grid Height="34">
<Label x:Name="label" Content="Curr Px" HorizontalAlignment="Left" Width="150"/>
<Label x:Name="lblCurrentPrice" Content="Label" Margin="150,0,0,0"/>
</Grid>
<Grid Height="34">
<Label x:Name="label2" Content="Trade Px" HorizontalAlignment="Left" Width="150"/>
<Label x:Name="lblTradePrice" Content="Label" Margin="150,0,0,0"/>
</Grid>
<Grid Height="34">
<Label x:Name="label4" Content="Qty Done" HorizontalAlignment="Left" Width="150"/>
<Label x:Name="lblQuantityDone" Content="Label" Margin="150,0,0,0"/>
</Grid>
<Grid Height="34">
<Label x:Name="label6" Content="Size" HorizontalAlignment="Left" Width="150"/>
<Label x:Name="lblSize" Content="Label" Margin="150,0,0,0"/>
</Grid>
<Grid Height="34">
<Label x:Name="label8" Content="Stk Px" HorizontalAlignment="Left" Width="150"/>
<Label x:Name="lblStockPrice" Content="Label" Margin="150,0,0,0"/>
</Grid>
<Grid Height="34">
<Label x:Name="label10" Content="Delta" HorizontalAlignment="Left" Width="150"/>
<Label x:Name="lblDelta" Content="Label" Margin="150,0,0,0"/>
</Grid>
</StackPanel>
</UserControl>
当你使用的用户控件MouseEnter事件,你需要确保你的用户控件里面的内容。我在这里使用它,它没有任何问题。 – Bojje
而且我还建议在使用WPF编程时使用MVVM,那么您将不需要这个后台代码。而是将属性绑定到Xaml控制器。 – Bojje
你可以显示你的UserControl吗?我无法在我身边重现您的问题。 – 3615