WPF 綁定自定義控件的依賴屬性到ViewModel


首先關於數據綁定的基礎知識,參見官方文檔:https://docs.microsoft.com/en-us/dotnet/desktop-wpf/data/data-binding-overview

從上面文檔中可以看出,數據綁定是在DependencyProperty與ViewModel的Property之間一種聯系。

 

所以我們需要在自定義控件里實現DependencyProperty, 在ViewModel上實現Property,即擁有get、set方法的字段。還有INotifyPropertyChanged : https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.inotifypropertychanged?redirectedfrom=MSDN&view=netframework-4.8

在使用framework里的控件時,我們一般不會指定BindingMode: https://docs.microsoft.com/en-us/dotnet/api/system.windows.data.bindingmode?view=netframework-4.8#System_Windows_Data_BindingMode_TwoWay

因為大部分控件都是默認TwoWay。

注意,這個默認,其實就是在framework里顯示指定了TwoWay。

所以當我們的自定義控件的DependencyProperty沒有被更新的時候,考慮要設置BindingMode

                BindsTwoWayByDefault = true,
                DefaultUpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged

完整的代碼,以Progress屬性為例:

        public int Progress
        {
            get { return (int)GetValue(ProgressProperty); }
            set { SetValue(ProgressProperty, value); }
        }

        public static readonly DependencyProperty ProgressProperty =
            DependencyProperty.Register("Progress", typeof(int), typeof(MyUserControl), new FrameworkPropertyMetadata(0, OnProgressChangedCallback, OnProgressCoerceValueCallback) {
                BindsTwoWayByDefault = true,
                DefaultUpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
            });

 

參考資料:

https://www.dominikschmidt.net/2010/12/net-c-binding-custom-dependencyproperty-to-viewmodel-property/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM