[英]Eventhandler for WPF control in DataTemplate
我一直在使用WPF,但遇到了與DataTemplates相關的問題。 我有一個名為DetailPage.xaml的視圖,該視圖使用了一個名為Detail.xaml的數據模板 。 我向此DataTemplate添加了一個文本框,並且我想處理TextChanged事件。 所以我做了這樣的事情:
<DataTemplate x:Name="DetailContent">
<Grid Margin="5" DataContext="{Binding Items[0]}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition MaxHeight="80"/>
</Grid.RowDefinitions>
<StackPanel Width="432">
<TextBox Name="NumeroParadaTB" Text="{Binding NumeroParada}" MaxLength="5" TextChanged="NumeroParadaTB_TextChanged" />
</StackPanel>
</Grid>
</DataTemplate>
然后,我在DetailPage.xaml.cs中創建了事件處理程序,如下所示:
protected async void NumeroParadaTB_TextChanged(object sender, TextChangedEventArgs e)
{
string nroParada = ((TextBox)sender).Text;
if(!string.IsNullOrEmpty(nroParada) && nroParada.IsDigitsOnly() && nroParada.Length == 5)
{
}
}
但是在運行時,拋出錯誤並指出事件處理程序不存在。 我想我以錯誤的方式使用了事件處理程序。
謝謝!
由於您正在使用數據綁定,因此我假設您有一些具有NumeroParada
屬性的類:
public class SomeClass : INotifyPropertyChanged
{
/* other code here */
public string NumeroParada
{
get { return numeroParada; }
set
{
if (numeroParada != value)
{
numeroParada = value;
OnPropertyChanged("NumeroParada");
}
}
}
private string numeroParada;
}
當UI將更新綁定源時,將觸發此屬性的設置器。 這是您的“ TextChanged
”事件。
請注意,默認情況下,失去焦點時, TextBox
更新Text
屬性。 如果要在用戶更改文本時執行任何操作,請更新綁定定義:
Text="{Binding NumeroParada, UpdateSourceTrigger=PropertyChanged}"
到現在為止還挺好。 但是這段代碼:
if(!string.IsNullOrEmpty(nroParada) && nroParada.IsDigitsOnly() && nroParada.Length == 5)
建議您正在嘗試實施由用戶輸入的價值驗證。 驗證在WPF是相當大的主題,我建議你閱讀像這樣選擇驗證方法。
您可以使用“事件到命令”邏輯來代替添加事件處理程序。 在ViewModel中創建一個Command並將其綁定到TextChanged事件。
<TextBox Text="{Binding SearchText, Mode=TwoWay}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="TextChanged">
<i:InvokeCommandAction Command="{Binding MyCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
System.Windows.Interactivity程序集中提供了交互觸發器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.