访问DataTemplate中的TextBoxes

时间:2013-02-05 10:18:30

标签: wpf data-binding

我知道类似的问题已在SO中多次询问过。但是他们没有解决我的问题,并且在理解这些答案时遇到一些困难。这是我的情况;我有ItemsControl我使用了ItemTemplate并绑定了一些数据。

<Window.Resources>        
    <DataTemplate x:Key="AdditionalFieldTemlate">
        <Grid>
            <TextBlock Text="{Binding InfoName}"/>
            <TextBox Text="{Binding InfoValue,Mode=TwoWay}" Name="CustomValue"/>
        </Grid>
    </DataTemplate>
</Window.Resources>
<Grid>
    <ItemsControl ItemsSource="{Binding AdditionalInformation}" x:Name="additionalInfo" ItemTemplate="{DynamicResource AdditionalFieldTemlate}"/>
</Grid>  

点击TextBox后,我需要将Button文本设置为空(datatemplate中的所有文本框文本)。不知道如何访问这些文本框。请帮帮我。

2 个答案:

答案 0 :(得分:1)

您通常不会访问TextBoxes(外观)....您可以访问绑定的数据。

因此,您可以按如下方式更改集合中的“数据”:

foreach (var item in AdditionalInformation)
{
    item.InfoValue = "";
}

然后将清空“TextBoxes”。

确保您已对INotifyPropertyChanged ....正在使用的类实施AdditionalInformation,以便在更改InfoValue属性时会发出通知。

答案 1 :(得分:0)

文本框中的文本数据绑定到类的InfoValue属性。像这样实现类和proprty:

class InfoClass: INotifyPropertyChanged
{
    private string _infoValue;

    ...

    public string InfoValue
    {
        get { return _infoValue; }
        set
        {
            _infoValue = value;
            OnNotifyPropertyChanged("InfoValue")
        }
    }

    ...

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string property)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(property));
    }
}

然后在您的按钮点击处理程序中执行colinsmith建议的操作(如果您使用MVVM方法,则执行命令)。绑定将通知更改,视图将更新。

相关问题