In WPF, how to add an EventHandler for a FrameworkElement designed in Template?

后端 未结 5 1399
被撕碎了的回忆
被撕碎了的回忆 2021-01-06 11:12

I have defined the following DataTemplate for ListBox items in an external resource dictionary:



        
5条回答
  •  旧巷少年郎
    2021-01-06 12:06

    Using the OnApplyTemplate approach will work if you if you're working with the ControlTemplate for a Control. For example, if you've subclassed TextBox you could do this like

    public class MyTextBox : TextBox
    {
        public override void OnApplyTemplate()
        {
            MySlider MySlider = GetTemplateChild("MySlider") as MySlider;
            if (MySlider != null)
            {
                MySlider.ValueChanged += new RoutedPropertyChangedEventHandler(MySlider_ValueChanged);
            }
            base.OnApplyTemplate();
        }
        void MySlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs e)
        {
            //...
        }
    }
    

    I don't think this approach will work in your situation however. You could use the Loaded event for ListBoxItem and find the Slider in the visual tree in the event handler

    
        
            
        
        
    
    

    Code behind

    private void ListBoxItem_Loaded(object sender, RoutedEventArgs e)
    {
        ListBoxItem listBoxItem = sender as ListBoxItem;
        Slider MySlider = GetVisualChild(listBoxItem);
        MySlider.ValueChanged += new RoutedPropertyChangedEventHandler(MySlider_ValueChanged);
    }
    void MySlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs e)
    {
    
    }
    

    GetVisualChild

    private static T GetVisualChild(DependencyObject parent) where T : Visual
    {
        T child = default(T);
    
        int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < numVisuals; i++)
        {
            Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
            child = v as T;
            if (child == null)
            {
                child = GetVisualChild(v);
            }
            if (child != null)
            {
                break;
            }
        }
        return child;
    }
    

提交回复
热议问题