[英]WPF two way data bind to custom data type in observable collection
我正在嘗試將數據綁定到WPF中的自定義數據類型屬性FormulaField
。 我不明白是否有什么我錯過了或者我想做什么不能做?
我遵循了如何綁定到一個原語的約定,發現它沒有工作, FormulaField
屬性沒有更新。 我還注意到自定義數據類型集方法永遠不會被命中。 我正在使用MVVM。
一個模型:
public class OBQModel : NotificationObject
{
private FormulaField _tovLitres;
public FormulaField TOVLitres
{
get
{
if (_tovLitres.UsesFormula)
{
_tovLitres.Value = ConversionHelper.USBarrelsToLitres(_tovBarrels);
}
return _tovLitres;
}
set
{
_tovLitres = value;
RaisePropertyChanged("TOVLitres");
}
}
}
NotificationObject
實現了INotifyPropertyChanged
:
public abstract class NotificationObject : DependencyObject, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged<T>(Expression<Func<T>> action)
{
var propertyName = GetPropertyName(action);
RaisePropertyChanged(propertyName);
}
private static string GetPropertyName<T>(Expression<Func<T>> action)
{
var expression = (MemberExpression)action.Body;
var propertyName = expression.Member.Name;
return propertyName;
}
protected internal void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
FormulaField看起來像這樣:
public class FormulaField
{
public bool UsesFormula { get; set; }
public double Value { get; set; }
}
編輯在FormulaField
實現INotifyPropertyChanged
會FormulaField
堆棧溢出...
public class FormulaField : INotifyPropertyChanged
{
public bool UsesFormula { get; set; }
public double Value
{
get
{
return Value;
}
set
{
Value = value;
}
}
public event PropertyChangedEventHandler PropertyChanged;
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
模型位於ViewModel中的ObservableCollection
內。
視圖的說明:
<StackPanel>
<DataGrid ItemsSource="{Binding OBQModelCollection}">
<DataGrid.Columns>
<DataGridTemplateColumn Header="new TOV (L)" Width="100">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox BorderThickness="0"
Text="{Binding TOVLitres.Value, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</StackPanel>
根據你所寫的內容,你在“LiquidGOVLitres”上提出INPC,這似乎沒有出現在你的代碼清單中,但你綁定到“TOVLitres”。
修復此不一致性會有所幫助,但如果您希望更改其成員作為UI的一部分,則還需要在FormulaField上實現INPC。
ETA:在對代碼清單進行澄清編輯之后,剩下的任務是在您的FormulaField類上實現INPC並相應地引發事件。
此外,如果您使用的是4.5,則可以調查新的“成員信息”類,這有助於避免在INPC中使用魔術字符串。
最后,為了語義清晰,將“Value”重命名為“FormulaValue”並不會有什么壞處......
為避免遞歸,請嘗試此模型...
private double _value;
public double Value
{
[DebuggerStepThrough]
get { return _value; }
[DebuggerStepThrough]
set
{
if (Math.Abs(value - _value) > Double.Epsilon)
{
_value = value;
OnPropertyChanged("Value");
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.