首页 新闻 赞助 找找看

wpf用户自定义控件里面button不响应事件,改为Window后一切正常

0
悬赏园豆:50 [已解决问题] 解决于 2013-10-27 13:44

这是为什么呢?比如click事件,如果是UserContorl不响应,但是改成Window窗体后又是正常的,怎么解决这么情况呢,求教。

wpf
翻墙小龙虾的主页 翻墙小龙虾 | 初学一级 | 园豆:34
提问于:2013-10-27 12:51
< >
分享
最佳答案
0

你的自定义控件继承了button吗? 你把你写的代码贴出来吧。

收获园豆:50
悟行 | 专家六级 |园豆:12559 | 2013-10-27 12:54
<UserControl x:Class="WpfApplication1.autoBox"
             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" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <UserControl.Resources>

        <DataTemplate x:Key="listboxtemplate">
            <StackPanel>
                <Image Source="{Binding}" Visibility="{Binding ImgVisibility}"
                        Width="16" Height="16" Stretch="Fill" Margin="2"></Image>
                <Button  Content="{Binding ButtonContent}"
                             Visibility="{Binding BtnVisibility}"
                             Foreground="Blue" Click="Button_Click" />
                <TextBlock Text="{Binding Path=Text}" Margin="2" ></TextBlock>
            </StackPanel>
        </DataTemplate>
    </UserControl.Resources>



    <StackPanel>
        <TextBox Name="tb" LostFocus="tb_LostFocus"/>
        <ListBox Name="lb" 
                 MaxHeight="150"
                 Canvas.Left="0" 
                 Canvas.Top="20" 
                 Visibility="Visible" 
                 ItemTemplate="{StaticResource listboxtemplate}">

        </ListBox>
    </StackPanel>

</UserControl>
View Code
翻墙小龙虾 | 园豆:34 (初学一级) | 2013-10-27 13:03
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for autoBox.xaml
    /// </summary>
    public partial class autoBox : UserControl
    {
        #region Members
        private ObservableCollection<AutoCompleteEntry> autoCompletionList;//数据源
        public ObservableCollection<AutoCompleteEntry> AutoCompletionList
        {
            get { return autoCompletionList; }
            set
            {
                autoCompletionList = value;
            }
        }

        private ObservableCollection<AutoCompleteEntry> selectList;//筛选后的数据
        public ObservableCollection<AutoCompleteEntry> SelectList
        {
            get { return selectList; }
            set
            {
                selectList = value;
            }
        }
        private delegate void TextChangedCallback();
        private bool insertText;//是否插入textbox
        private int searchThreshold;//文本框最少输入多少字符开始匹配
        public int Threshold
        {
            get { return searchThreshold; }
            set { searchThreshold = value; }
        }
        private bool autoBoxIsEnable = true;//是否可用
        public bool AutoBoxIsEnable
        {
            get { return autoBoxIsEnable; }
            set { autoBoxIsEnable = value; }
        }
        public object SelectListItem //当前选择项
        {
            get { return lb.SelectedItem; }
            set { lb.SelectedItem = value; }
        }
        private bool isAddButtonInTheFirst = false;//是否第一行添加按钮
        public bool IsAddButtonInTheFirst
        {
            get { return isAddButtonInTheFirst; }
            set { isAddButtonInTheFirst = value; }
        }
        private double boxWidth;
        public double BoxWidth
        {
            get { return tb.Width; }
            set
            {
                tb.Width = value;
                lb.Width = value;
            }
        }

        private double boxHeight;
        public double BoxHeight
        {
            get { return tb.Height; }
            set
            {
                tb.Height = value;
            }
        }
        private double boxMaxHeight;
        public double BoxMaxHeight
        {
            get { return lb.MaxHeight; }
            set { lb.MaxHeight = value; }
        }
        private string imgSource;
        public string ImgSource
        {
            get { return imgSource; }
            set { imgSource = value; }
        }
        #endregion

        #region Constructor
        public autoBox()
        {
            InitializeComponent();
        }
        public void Init(List<AutoCompleteEntry> list, bool isAddButton)//初始化
        {
            autoCompletionList = new ObservableCollection<AutoCompleteEntry>(list);
            searchThreshold = 1;
            lb.IsEnabled = AutoBoxIsEnable;
            lb.IsSynchronizedWithCurrentItem = true;
            lb.IsTabStop = false;
            lb.Visibility = Visibility.Collapsed;
            tb.TextChanged += new TextChangedEventHandler(textBox_TextChanged);
            tb.VerticalContentAlignment = VerticalAlignment.Center;
            tb.KeyUp += new KeyEventHandler(textBox_keyDown);
            tb.IsEnabled = AutoBoxIsEnable;
            IsAddButtonInTheFirst = isAddButton;
        }
        #endregion

        #region Methods
        private void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
          
        }
        private void textBox_keyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Down)
            {
                if (lb.HasItems && lb.SelectedIndex < lb.Items.Count)
                {
                    lb.SelectedIndex = lb.SelectedIndex + 1;
                    lb.ScrollIntoView(lb.SelectedItem);
                }
            }
            if (e.Key == Key.Up && lb.SelectedIndex > 0)
            {
                if (lb.HasItems)
                {
                    lb.SelectedIndex = lb.SelectedIndex - 1;
                    lb.ScrollIntoView(lb.SelectedItem);
                }
            }
            if (e.Key == Key.Enter && lb.SelectedItem != null)
            {
           
                if (IsAddButtonInTheFirst && lb.SelectedIndex < 1)
                {
                    return;
                }
                tb.Text = (SelectListItem as ListBoxItem).Content.ToString();
                tb.Focus();
                if (tb.Text.Trim().Length > 0)
                {
                    tb.Select(tb.Text.Trim().Length, 0);
                }
                if (lb.HasItems)
                {
                    lb.Items.Clear();
                }
            }
        }
        private void TextChanged()
        {
            #region 
            lb.ItemsSource = null;
            lb.SelectionChanged -= new SelectionChangedEventHandler(listBox_SelectionChanged);
            if (selectList != null)
            {
                selectList.Clear();
            }
            if (tb.Text.Length >= searchThreshold)
            {
                SelectList = new ObservableCollection<AutoCompleteEntry>(autoCompletionList.Where(p => p.Text.Contains(tb.Text.Trim())));
                if (SelectList.Count > 0)
                {
                    if (!IsAddButtonInTheFirst)
                    {
                        lb.ItemsSource = selectList;
                        // lb.DisplayMemberPath = "Text";
                        lb.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        AutoCompleteEntry temp = new AutoCompleteEntry();
                        temp.BtnVisibility = Visibility.Visible;
                        temp.ImgVisibility = Visibility.Visible;
                        temp.ButtonContent = "添加";
                        selectList.Insert(0, temp);
                        lb.ItemsSource = selectList;
                        // lb.DisplayMemberPath = "Text";
                        lb.Visibility = Visibility.Visible;
                    }
                }
                else lb.Visibility = Visibility.Collapsed;
            }
            else
            {
                lb.Visibility = Visibility.Collapsed;
            }
            lb.SelectionChanged += new SelectionChangedEventHandler(listBox_SelectionChanged);
            #endregion
          
        }
        private void textBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (insertText == true) insertText = false;
            else
            {
                TextChanged();
            }
        }
        #endregion

        private void tb_LostFocus(object sender, RoutedEventArgs e)
        {
            if (!lb.IsFocused)
            {
                lb.Visibility = Visibility.Collapsed;
            }
        }
      
        private void Button_Click(object sender, RoutedEventArgs e)
        {

        }
    }
}
View Code

 

<UserControl x:Class="WpfApplication1.autoBox"
             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" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <UserControl.Resources>

        <DataTemplate x:Key="listboxtemplate">
            <StackPanel>
                <Image Source="{Binding}" Visibility="{Binding ImgVisibility}"
                        Width="16" Height="16" Stretch="Fill" Margin="2"></Image>
                <Button  Content="{Binding ButtonContent}"
                             Visibility="{Binding BtnVisibility}"
                             Foreground="Blue" Click="Button_Click" />
                <TextBlock Text="{Binding Path=Text}" Margin="2" ></TextBlock>
            </StackPanel>
        </DataTemplate>
    </UserControl.Resources>



    <StackPanel>
        <TextBox Name="tb" LostFocus="tb_LostFocus"/>
        <ListBox Name="lb" 
                 MaxHeight="150"
                 Canvas.Left="0" 
                 Canvas.Top="20" 
                 Visibility="Visible" 
                 ItemTemplate="{StaticResource listboxtemplate}">

        </ListBox>
    </StackPanel>

</UserControl>
View Code
翻墙小龙虾 | 园豆:34 (初学一级) | 2013-10-27 13:04

上面的就是代码,主要是button的事件不响应,求教。

翻墙小龙虾 | 园豆:34 (初学一级) | 2013-10-27 13:06

@翻墙小龙虾: 把click换成PreviewMouseDown/PreviewMouseUp 这两个的一个事件试试吧。

悟行 | 园豆:12559 (专家六级) | 2013-10-27 13:10

@荒野的呼唤: 这两个可以,click不行,好奇怪。初学不是很懂,为什么会有这种情况啊?

翻墙小龙虾 | 园豆:34 (初学一级) | 2013-10-27 13:16

@翻墙小龙虾: 因为click有可能有别的元素执行这个事件。

事件路由
对逻辑树和可视树有所了解很有必要,因为路由事件主要是根据可视树进行路由。路由事件支持三种路由策略:气泡、隧道和直接。
气泡事件最为常见,它表示事件从源元素扩散(传播)到可视树,直到它被处理或到达根元素。这样您就可以针对源元素的上方层级对象处理事件。例如,您可向嵌入的 Grid 元素附加一个 Button.Click 处理程序,而不是直接将其附加到按钮本身。气泡事件有指示其操作的名称(例如,MouseDown)。
隧道事件采用另一种方式,从根元素开始,向下遍历元素树,直到被处理或到达事件的源元素。这样上游元素就可以在事件到达源元素之前先行截取并进行处理。根据命名惯例,隧道事件带有前缀 Preview(例如 PreviewMouseDown)。
 
你必须对整个事件有所了解,详细请看这:
悟行 | 园豆:12559 (专家六级) | 2013-10-27 13:23

@荒野的呼唤: 感谢

翻墙小龙虾 | 园豆:34 (初学一级) | 2013-10-27 13:44
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册