我有一个名为MainWindow
的窗口,其中包含2个UserControls:
SearchBox
和
CustomerList
当有人输入SearchBox时,我想相应地更改CustomerList。
问题:CustomerList
知道TextChanged
事件已在SearchBox
中执行的最佳方法是什么?
现在我将SearchBox
定义为:
public class SearchSubmittedEventArgs : EventArgs
{
public string Term { get; set; }
public SearchSubmittedEventArgs(string term)
{
Term = term;
}
}
public partial class SearchBox : UserControl
{
public event EventHandler<SearchSubmittedEventArgs> SearchSubmitted;
public SearchBox()
{
InitializeComponent();
}
private void SearchTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (SearchSubmitted != null) SearchSubmitted.Invoke(this, new SearchSubmittedEventArgs(((TextBox)sender).Text));
}
}
和MainWindow
具有以下XAML和EventHandler:
<UserControls:SearchBox SearchSubmitted="SearchSubmitted_Invoked" />
private void SearchSubmitted_Invoked(object sender, SearchSubmittedEventArgs e)
{
// I know SearchBox has been typed into
// but I don't know how best to inform CustomerList
}
我是否需要将活动从SearchSubmitted_Invoked
传递给CustomerList
?有没有办法让我直接从SearchBox
传递给CustomerList
?
答案 0 :(得分:3)
我认为你可以订阅这个活动...这些内容:
var search = new SearchBox();
var cust = new CustomerList();
search.SearchSubmitted += (s,e)=>{ cust.Update(e.Term); }
希望它可以帮助您找到一种方法......
答案 1 :(得分:0)
这些控件是否彼此靠近?那么用它们内部烘焙一个新的用户控件可能是有意义的。该外部用户控件是应该进行事件处理的控件。