2013-02-05 32 views
0

我知道類似這樣的問題已經在SO中問了好幾次了。但他們中沒有人能夠解決我的問題,並且在理解這些答案時遇到了一些困難這是我的情況;我有一個ItemsControl我已經使用ItemTemplate並綁定了一些數據。訪問DataTemplate中的文本框

<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文本爲空(裏面的DataTemplate所有文本框的文本),一旦點擊一個Button。不知道如何訪問這些文本框。請幫幫我。

回答

1

您通常不訪問文本框(外觀)....您訪問被綁定到的數據。

所以你可以改變你的集合中的「數據」,如下所示:

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

的「文本框」將被清空。

請確保您已對AdditionalInformation ....所使用的類實施了INotifyPropertyChanged ....以便當InfoValue屬性發生更改時會引發通知。

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方法去)。綁定將被通知到更改並且視圖將被更新。