wpf trouble using dependency properties in a UserControl

前端 未结 3 1669
萌比男神i
萌比男神i 2021-01-12 08:01

I made a UserControl that is meant to be updated once every few seconds with data from a serial port. This UserControl should be very simple, consisting of a Label for a fi

3条回答
  •  梦毁少年i
    2021-01-12 08:24

    You really don't need a dependency property on your user control, in fact you should strive to keep user controls without anything special in the code-behind, custom Controls should be used for that.

    You should define your UserControl like this (without any code behind):

    
        
            
    

    Then, make sure your business object implements INotifyPropertyChanged, because you cannot update from your business object efficiently without modifying it at least this much. The fieldName is just an example how you could bind the display name on the label automatically to a property on your business object.

    Then, simply make sure the DataContext of your UserControl is your business object.

    How will this work? The Label.Content property is a DependencyProperty and will support binding itself. Your business object implements INotifyPropertyChanged and thus supports updates to binding - without it, the binding system does not get notified when your field's value changes, regardless if you bound it to a DependencyProperty on one end.

    And if you want to reuse this user control elsewhere, simply place a desired instance of your business object to the DataContext of the desired LabeledField control. The binding will hook up itself from the DataContext.

提交回复
热议问题