我試圖實現更新搜索短語更改時更新TreeView的實時更新搜索欄,但我沒有完全設法讓它更新我想要的方式。WPF搜索框和數據綁定到樹視圖
所有項目都在應用程序啓動時顯示在樹視圖中(它現在只包含一個子級)。當我輸入文本框並調用PropertyChanged事件時,SearchPhrase屬性也會正確更新,但不會調用Items get。我的猜測是它與演示模型Items屬性有關。我對嗎?
這裏是我的XAML:
<Border BorderBrush="Black">
<TextBox VerticalAlignment="Top" x:Name="phrase" Text="{ Binding Path=SearchPhrase, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged }" Height="24" />
</Border>
<TreeView Height="200" Background="Gainsboro" Name="list" ItemsSource="{ Binding Path=Items, Mode=OneWay, UpdateSourceTrigger=PropertyChanged }" ItemTemplate="{StaticResource dataTemplate}" />
這是我的演示模型:
public class ProjectListPM : BasePM
{
private List<AnalysisInfo> items;
private String searchPhrase;
/// <summary>
/// Gets or sets the search phrase.
/// </summary>
public String SearchPhrase {
get
{
return this.searchPhrase;
}
set
{
if (value != null)
{
this.searchPhrase = value;
FirePropertyChanged<ProjectListPM>(o => o.SearchPhrase);
}
}
}
/// <summary>
/// The list of analysises to display in the list.
/// </summary>
public List<AnalysisInfo> Items {
get
{
return
items.OrderByDescending(i => i.GetSearchRelevanceTo(SearchPhrase)).Where(
i => i.GetSearchRelevanceTo(SearchPhrase) > 0).ToList();
}
set
{
if (value != null)
{
this.items = value;
FirePropertyChanged<ProjectListPM>(o => o.Items);
}
}
}
public ProjectListPM()
{
this.items = new List<AnalysisInfo>();
this.SearchPhrase = String.Empty;
}
}
public class BasePM : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Called when a property is changed.
/// </summary>
/// <typeparam name="T">Type</typeparam>
/// <param name="exp">Function</param>
protected void FirePropertyChanged<T>(Expression<Func<T, Object>> exp)
{
string propertyName;
if (exp.Body is UnaryExpression)
propertyName = ((MemberExpression)((UnaryExpression)exp.Body).Operand).Member.Name;
else
propertyName = ((MemberExpression)exp.Body).Member.Name;
if (PropertyChanged != null)
{
//Switch to UI thread
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
這正是我發現自己的解決方案。謝謝,雖然:) – atsjoo 2009-06-16 07:46:43