當試圖通過XAML
將ListView
綁定到ObservableCollection
時,ListView
未更新,並且最初使用空值加載。WPF數據綁定不能通過XAML工作(僅通過代碼)
通過XAML
History.xaml.cs
DataContext = this;
History.xaml:
<ListView x:Name="lvHistory" ItemsSource="{Binding Source=history}" BorderThickness="0" Margin="0,0,0,0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Column="2" util:GridViewSort.AutoSort="True" SizeChanged="lvHistory_SizeChanged">
通過代碼
當操作的方式從代碼的結合,該綁定工作正常。
History.xaml
<ListView x:Name="lvHistory" BorderThickness="0" Margin="0,0,0,0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Column="2" util:GridViewSort.AutoSort="True" SizeChanged="lvHistory_SizeChanged">
History.xaml.cs
DataContext = this;
lvHistory.ItemsSource = history;
只需通過代碼添加的ItemsSource和XAML刪除它,代碼工作正常。我錯過了什麼?我如何通過純XAML創建綁定?
歷史:
public ObservableCollection<LocateElement> history { get; private set; }
代碼更新列表:
public void Update()
{
if (updater.IsBusy) updatePending = true;
else
{
searchValue = txtSearch.Text.Trim();
updatePending = false;
updater.RunWorkerAsync();
}
}
private void updateContent(object sender, DoWorkEventArgs e)
{
try
{
Globals.Variables.logger.Info("Locate History: Updating");
using (var db = new Data.DataManager())
{
var history = db.LocateHistory.Where(o => o.ReceivedBy == Globals.Variables.loginDetails.UserID);
e.Result = filterResults(history);
}
}
catch (Exception er)
{
Globals.Variables.logger.Error(er);
}
}
private void updateFinished(object sender, RunWorkerCompletedEventArgs e)
{
List<LocateElement> r = (List<LocateElement>)e.Result;
history.Clear();
foreach (LocateElement l in r)
{
history.Add(l);
}
if (updatePending) Update();
//else Wpf.Util.GridViewSort.ReapplySort(lvHistory);
}
private List<LocateElement> filterResults(IQueryable<LocateElement> list)
{
List<LocateElement> history = new List<LocateElement>();
foreach (LocateElement l in list)
{
if (searchValue != "")
{
// Use the parameters to filter the results.
Regex reg = new Regex(WildcardToRegex(searchValue));
if (reg.IsMatch(l.Serial) || reg.IsMatch(l.Asset) || reg.IsMatch(l.DeviceType) || reg.IsMatch(l.Company) || (l.ReceivedFrom != null && reg.IsMatch(l.ReceivedFrom.Name)) || (l.ReceivedTo != null && reg.IsMatch(l.ReceivedTo.Name)) || reg.IsMatch(l.Row) || reg.IsMatch(l.Shelf) || reg.IsMatch(l.Bin) || reg.IsMatch(l.DateReceived.ToString()))
{
history.Add(l);
}
}
else
{
history.Add(l);
}
}
return history;
}
設置'ItemsSource =「{綁定歷史}」'工作。值已正確更新,無需添加通知。 – teynon
正如@McAden所解釋的那樣,您可能會看到像這樣寫成的綁定「ItemsSource =」{Binding Path = history}'。 – deloreyk