我的綁定有些問題。但我不能找到它wpf數據綁定時機問題
我有一個狀態類型控件(用戶控件),有一個ItemsControl與結合,依靠一個ViewModelBase對象,它提供BrokenRules的名單,像這樣的:
<ItemsControl ItemsSource="{Binding BrokenRules}" >
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock>
<Hyperlink Foreground="Red" >
<TextBlock Text="{Binding Description}" />
</Hyperlink>
</TextBlock>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
結合以我想要的方式工作,即顯示任何和所有破碎的規則說明。規則幾乎只是一個描述和一個委託,在規則被告知驗證自己時執行。
在規則被要求驗證自己之前,大多數規則都有預先知道的描述。例如,如果驗證委託!Name.IsNullOrEmptyAfterTrim()失敗,那麼「Name is not valued value」就是錯誤描述。
問題出現在一個特定的規則中,該規則檢查重複的名稱。如果重複檢查失敗,我想能夠說出重複的值是什麼,這是不可能知道的。所以規則需要在驗證委託執行時更新描述。
當我單元測試或在驗證委託中留下調試跟蹤時,更新了損壞的規則描述。但是當我運行應用程序時,破損的規則描述是之前被更新的內容。
因此,我猜測我的綁定是不正確的。任何人都可以提出什麼問題/修復?
乾杯,
Berryl
UPDATE ====================
這是從我ViewModelBase類代碼:
private readonly List<RuleBase> _rules = new List<RuleBase>();
// inheritors add rules as part of construction
protected void _AddRule(RuleBase rule) { _rules.Add(rule); }
public ObservableCollection<RuleBase> BrokenRules { get { return _brokenRules; } }
protected ObservableCollection<RuleBase> _brokenRules;
public virtual IEnumerable<RuleBase> GetBrokenRules() {
return GetBrokenRules(string.Empty);
}
public virtual IEnumerable<RuleBase> GetBrokenRules(string property) {
property = property.CleanString();
_brokenRules = new ObservableCollection<RuleBase>();
foreach (var r in _rules) {
// Ensure we only validate this rule
if (r.PropertyName != property && property != string.Empty) continue;
var isRuleBroken = !r.ValidateRule(this);
if (isRuleBroken) _brokenRules.Add(r);
return _brokenRules;
}
您的ViewModelBase類是否實現INotifyPropertyChanged?即。 UI是否知道Description屬性何時更改? – 2010-07-16 01:20:21
您是否將項目添加到BrokenRules集合中?它是一個ObservableCollection? – Anero 2010-07-16 01:25:45
@Matt。是的,VmBase實現INPC。至於你的答案的第二部分,我認爲Aero接近它,如果我不每次都重新創建集合實例,那麼UI將保持與更改同步。需要通過tho工作。歡呼 – Berryl 2010-07-16 02:50:09