WPF: PropertyChangedCallback triggered only once

前端 未结 4 523
自闭症患者
自闭症患者 2021-01-02 06:57

I have a user control, which exposes a DependencyProperty called VisibileItems Every time that property gets updated, i need to trigger another event. To achieve that, i ad

4条回答
  •  说谎
    说谎 (楼主)
    2021-01-02 07:22

    I have the same issue in my code and Luke is right. I called SetValue by mystake inside the PropertyChangedCallback causing a potential infinite loop. WPF prevent this disabling silently the callback !!

    my WPF UserControl is

    PatchRenderer
    

    my C# property is Note:

        [Description("Note displayed with star icons"), 
        Category("Data"),
        Browsable(true), 
        EditorBrowsable(EditorBrowsableState.Always),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public int Note
        {
            get { return (int)GetValue(NoteProperty); }
            set { SetValue(NoteProperty, value); /* don't put anything more here */ }
        }
    

    my WPF property

    public static readonly DependencyProperty 
            NoteProperty = DependencyProperty.Register("Note",
            typeof(int), typeof(PatchRenderer),
            new PropertyMetadata(
                new PropertyChangedCallback(PatchRenderer.onNoteChanged)
                ));
    
        private static void onNoteChanged(DependencyObject d,
                   DependencyPropertyChangedEventArgs e)
        {
            // this is the bug: calling the setter in the callback
            //((PatchRenderer)d).Note = (int)e.NewValue;
    
            // the following was wrongly placed in the Note setter.
            // it make sence to put it here.
            // this method is intended to display stars icons
            // to represent the Note
            ((PatchRenderer)d).UpdateNoteIcons();
        }
    

提交回复
热议问题