DataTemplate中WPF控件的Eventhandler

时间:2014-12-04 13:20:34

标签: c# wpf xaml

我一直在使用WPF,我遇到了与DataTemplates相关的问题。 我有一个名为 DetailPage.xaml 的视图,此视图使用名为 Detail.xaml 的DataTemplate。我在这个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)
        {

        }
    }

但是在运行时,会抛出错误,说事件处理程序不存在。我想我是以错误的方式使用事件处理程序。

谢谢!

2 个答案:

答案 0 :(得分:3)

由于您正在使用数据绑定,我假设您有一些具有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将更新绑定源时,将触发此属性的setter。这是您的“TextChanged”活动。

注意,默认情况下,TextBox会在失去焦点时更新Text属性。如果要在用户更改文本时执行任何操作,请更新绑定定义:

Text="{Binding NumeroParada, UpdateSourceTrigger=PropertyChanged}"

到目前为止一切顺利。但是这段代码:

if(!string.IsNullOrEmpty(nroParada) && nroParada.IsDigitsOnly() && nroParada.Length == 5)

建议您尝试实施用户输入的值验证。 WPF中的验证是一个相当大的主题,我建议您阅读类似this的内容来选择验证方法。

答案 1 :(得分:0)

您可以使用Event to Command逻辑,而不是添加Event处理程序。在ViewModel中创建一个命令并将其绑定到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程序集中可用的交互触发器。