开发者

WPF, getting two way binding to work on custom control

开发者 https://www.devze.com 2022-12-26 08:25 出处:网络
Two way binding does not work on my custom control with the following internals: public partial class ColorInputControl

Two way binding does not work on my custom control with the following internals:

 public partial class ColorInputControl 
    {
        public ColorInputControl()
        {
            InitializeComponent();
            colorPicker.AddHandler(ColorPicker.SelectedColorChangedEvent, 
               new RoutedPropertyChangedEventHandler<Color>( SelectedColorChanged));;
            colorPicker.AddHandler(ColorPicker.CancelEvent,
               new RoutedPropertyChangedEventHandler<Color>(OnCancel));            
        }      

        public static readonly DependencyProperty SelectedColorProperty =
            DependencyProperty.Register
            ("SelectedColor", typeof(Color), typeof(ColorInputControl),
            new PropertyMetadata(Colors.Transparent, null));



        public Color SelectedColor
        {
            get
            {
                return (Color)GetValue(SelectedColorProperty);
                //return colorPicker.SelectedColor;
            }
            set
            {
                SetValue(SelectedColorProperty, value);
                colorPicker.SelectedColor = value;           
            }
        }

        private void SelectedColorChanged(object sender, RoutedPropertyChangedEventArgs<Color> e)
        {
            SetValue(SelectedColorProperty, colorPicker.SelectedCol开发者_运维百科or);                
        }       

    }

SelectedColor is being bound to a property that fires INotifyPropertyChanged event control when it changes. However, I cannot get two-way binding to work. Changes from the UI are pesisted to the data source. However, changes originating from the data source are not reflected on the UI.

What did I miss? TIA.


Never do any work (updating the color picker) in the SelectColor helpers. Those are convinence wrappers and are not guarranted to be called. (As you can see in your two way binding.) Add a PropertyChangedCallback to your SelectedColorProperty metadata. Do your work in there.

0

精彩评论

暂无评论...
验证码 换一张
取 消