【问题标题】:Generic MouseButtonEventHandler for TextBox and Label用于文本框和标签的通用 MouseButtonEventHandler
【发布时间】:2020-05-20 17:26:11
【问题描述】:

通过 MacDonald 的“Pro WPF 4.5 in C#”学习 WPF,重点关注第 5 章,事件。 我将如何编写一个可与​​标签和文本框一起使用的通用事件处理程序来处理初始化拖放过程的 MouseDown 事件? 这是我的 TextBox 处理程序:

private void tBSource_MouseDown(object sender, EventArgs e) {
            TextBox tBox = (TextBox)sender;
            DragDrop.DoDragDrop(tBox, tBox.Text, DragDropEffects.Copy);
}

还有我的标签处理程序:

private void lblSource_MouseDown(object sender, EventArgs e) {
            Label lbl = (Label)sender;
            DragDrop.DoDragDrop(lbl, lbl.Content, DragDropEffects.Copy);
}

如您所见,我使用的是 Content 属性和 Text 属性,具体取决于启动事件的对象。如果我尝试对两个发件人使用相同的属性,我会收到构建错误(无论我使用哪个)。如果我能避免重复,我会很高兴。我应该将条件分块到另一个函数中并在处理程序中调用它以确定应该使用什么属性?

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    你可以这样做:

    private void Generic_MouseDown(object sender, EventArgs e)
        {
            object contentDrop = string.Empty;
            //Label inherits from ContentControl so it doesn't require more work to make work for all controls inheriting from ContentControl
            if (sender is ContentControl contentControl)
            {
                //If you don't want to filter other content than string, you can remove this check you make contentDrop an object
                if (contentControl.Content is string)
                {
                    contentDrop = contentControl.Content.ToString();
                }
                else
                {
                    //Content is not a string (there is probably another control inside)
                }
            }
            else if (sender is TextBox textBox)
            {
                contentDrop = textBox.Text;
            }
            else
            {
                throw new NotImplementedException("The only supported controls for this event are ContentControl or TextBox");
            }
            DragDrop.DoDragDrop((DependencyObject)sender, contentDrop, DragDropEffects.Copy);
        }
    

    如果您有任何问题,请告诉我

    【讨论】:

    • 非常清晰和有指导意义的答案,谢谢。我确实有一个问题:如果我想同时捕获 TextBoxes 和 TextBlocks 怎么办?据我所知,它们不共享单个共享父对象。我是否需要添加另一个 else if 块来捕获 TextBlock?我不得不承认,我发现 WPF 控件的继承结构有点迟钝。
    • 是的,我也检查过,我希望 Textblock 和 TextBox 与 TextProperty 有一个共享的父级,但由于不是这种情况,您必须添加另一个 else if 块。我发现这篇关于 TextProperty 的帖子真的很有趣:stackoverflow.com/a/15236596/13448212
    猜你喜欢
    • 2015-08-23
    • 1970-01-01
    • 2019-03-04
    • 2010-11-13
    • 1970-01-01
    • 2012-03-22
    • 2014-07-20
    • 2023-03-09
    • 2018-03-17
    相关资源
    最近更新 更多