如何在代码隐藏中处理TextBlock中的MouseDown事件?

时间:2017-01-13 21:09:26

标签: c# wpf visual-studio events

我有ListBox TextBlocks作为列表:

<ListBox Grid.Row="1" Margin="5">
 <TextBlock Name="Address1" MouseDown="SongAddress"/>
 <TextBlock Name="Address2" MouseDown="SongAddress"/>
 <TextBlock Name="Address3" MouseDown="SongAddress"/>
 <TextBlock Name="Address4" MouseDown="SongAddress"/> 
</ListBox>

有四个TextBlocks,每个都有MouseDown事件。我想为每一个操作采取不同的操作,我如何处理code-behind哪一个被点击?

3 个答案:

答案 0 :(得分:0)

StackOverflow上有许多问题可以解决这个问题。我假设您熟悉WPF中的how to write the code for an event handler

签名看起来像:

private void SongAddress(object sender, RoutedEventArgs eventArgs)

然后 - 在你提到的情况下 - 取决于你如何你处理这个事件。您可以为每个按钮实现单独的事件处理程序,也可以将sender强制转换为类型TextBlock并从中获取区分属性。

未经请求的意见

包含类似的Name属性值和相同的MouseDown事件处理程序值会暗示每个TextBlock共享一些概念上相似的目的。您可能想知道您是否确实需要四个单独的句柄,或者您是否可以通过更好地建模您的域来处理您要完成的任务。

答案 1 :(得分:0)

我认为您需要使用预览
并命名TextBox

    <TextBox x:Name="tb01" PreviewMouseDown="tb01_PreviewMouseDown"/>

    private void tb01_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        if (sender is TextBox)
        {
            TextBox tb = (TextBox)sender;
            string s = tb.Name;
        }
    }

答案 2 :(得分:-1)

你尝试过使用不同的方法吗?

<ListBox Grid.Row="1" Margin="5">
 <TextBlock Name="Address1" MouseDown="SongAddress1"/>
 <TextBlock Name="Address2" MouseDown="SongAddress2"/>
 <TextBlock Name="Address3" MouseDown="SongAddress3"/>
 <TextBlock Name="Address4"  MouseDown="SongAddress4"/> </ListBox>

或者也许是Switch Case?

private void SongAddress(object sender, MouseButtonEventArgs e)
{
    switch (((TextBlock) sender).Name)
    {
        case "Address1":
            //dosomething
            break;
        case "Address2":
            //dosomething
            break;
        case "Address3":
            //dosomething
            break;
        case "Address4":
            //dosomething
            break;
    }
}
相关问题