您絕對只需要一個地方進行更新。
你沒有提到你有什麼樣的UI(Winforms,WPF - 假設你在談論桌面應用程序)。
我建議使用MVVM風格 - 它將適用於Winforms和WPF。
Public Class USBViewModel
Implements INotifyPropertyChanged
Private _Quantity As Integer
Public Property Quantity As Integer
Get
Return _Quantity
End Get
Set(value As Integer)
If value = _Quantity Then Exit Property
' Here you can update value to the USB
_Quantity = value
RaisePropertyChanged()
End Set
End Property
#Region "INotifyPropertyChanged"
Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
Private Sub RaisePropertyChanged(<CallerMemberName> Optional propertyName As String = Nothing)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
End Sub
#End region
End Class
然後,您可以將一個(相同)USBViewModel實例綁定到您的控件。
您可以創建Format
和Parse
事件處理程序,以將原始單位轉換爲要顯示和返回的單位。
對於的WinForms例如文本框可以界定如下:
Public Class YourForm
Private ReadOnly _ViewModel As USBViewModel
Public Sub New()
InitializeComponents()
_ViewModel = new USBViewModel()
var unitOneBunding = new Binding("Text", _ViewModel, "Quantity", True);
unitOneBunding.Format += bindUnitOne_Format;
unitOneBunding.Parse += bindUnitOne_Parse;
TextBoxUnitOneQuantity.DataBindings.Add(unitOneBunding);
End Sub
private void bindUnitOne_Format(object sender, ConvertEventArgs e)
{
int originalUnitValue = (int)e.Value;
int unitOneValue = ConvertToUnitOne(originalUnitValue);
e.Value = unitOneValue;
}
private void bindUnitOne_Parse(object sender, ConvertEventArgs e)
{
int unitOneValue = (int)e.Value;
int originalUnitValue = ConvertToOriginalUnit(unitOneValue);
e.Value = originalUnitValue;
}
End Class
自定義控件你可以通過同一實例的自定義控件的構造,有其綁定到相同的屬性。
此解決方案基於INotifyPropertyChanged
和數據綁定。
當您使用數據綁定控件時,將「偵聽」INotifyPropertyChanged
事件,並在值更改時自動更新。
在用戶更新控件的情況下,控件將調用有界屬性的setter。
我修改了我的文章,指定我正在製作Winforms應用程序。 DataBindings似乎是我在處理這個問題之前就無知的工具?谷歌搜索數據綁定有幫助。但是,我並不立即看到不同綁定控件如何知道在不同單元中顯示相同的值。 – BigBobby
@BigBobby,你可以使用'DataBinding.Format'和'DataBInding.Parse'事件將一個單位轉換爲另一個單位,查看我更新的答案 – Fabio