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

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

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



        
5条回答
  •  隐瞒了意图╮
    2021-01-06 11:56

    Method 1: Use your own control inherited from Slider:

    public class SpecialSlider : Slider
    {
        public SpecialSlider()
        {
            ValueChanged += OnValueChanged;
        }
    
        private void OnValueChanged(object sender, RoutedPropertyChangedEventArgs e)
        {
            // ...
        }
    }  
    

    Method 2: use behaviors from System.Windows.Interactivity.dll assembly (available through the NuGet):

    public class SpecialSliderBehavior : Behavior
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.ValueChanged += OnValueChanged;
        }
    
        protected override void OnDetaching()
        {
            base.OnDetaching();
            AssociatedObject.ValueChanged -= OnValueChanged;
        }
    
        private void OnValueChanged(object sender, RoutedPropertyChangedEventArgs e)
        {
            // ...
        }
    }
    

    This is how to attach it:

    ...
    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
    ...
    
        
            
                
            
        
    
    

提交回复
热议问题