Binding to static property

后端 未结 12 2307
夕颜
夕颜 2020-11-22 05:14

I\'m having a hard time binding a simple static string property to a TextBox.

Here\'s the class with the static property:



        
12条回答
  •  梦如初夏
    2020-11-22 05:50

    As of WPF 4.5 you can bind directly to static properties and have the binding automatically update when your property is changed. You do need to manually wire up a change event to trigger the binding updates.

    public class VersionManager
    {
        private static String _filterString;        
    
        /// 
        /// A static property which you'd like to bind to
        /// 
        public static String FilterString
        {
            get
            {
                return _filterString;
            }
    
            set
            {
                _filterString = value;
    
                // Raise a change event
                OnFilterStringChanged(EventArgs.Empty);
            }
        }
    
        // Declare a static event representing changes to your static property
        public static event EventHandler FilterStringChanged;
    
        // Raise the change event through this static method
        protected static void OnFilterStringChanged(EventArgs e)
        {
            EventHandler handler = FilterStringChanged;
    
            if (handler != null)
            {
                handler(null, e);
            }
        }
    
        static VersionManager()
        {
            // Set up an empty event handler
            FilterStringChanged += (sender, e) => { return; };
        }
    
    }
    

    You can now bind your static property just like any other:

    
    

提交回复
热议问题