2017-06-27 34 views
0

我需要更新用於在運行時加載listview的DataTemplate內的文本塊。每次用戶點擊遞增或遞減按鈕時,lblRepeatNum都必須相應地遞增或遞減。UWP Listview - 在運行時更新DataTemplate中的textblock

我很難從按鈕的單擊事件中訪問文本塊。請幫忙。

XAML &下面的c#代碼。

<ListView x:Name="lvBuildYourRuqya" Grid.Row="1"> 

     <ListView.ItemContainerStyle> 
      <Style TargetType="ListViewItem"> 
       <Setter Property="HorizontalContentAlignment" Value="Stretch" /> 
      </Style> 
     </ListView.ItemContainerStyle> 

     <ListView.ItemTemplate> 
      <DataTemplate> 

       <RelativePanel> 
        <TextBlock x:Uid="lblVerseName" x:Name="lblVerseName" Height="35" Text="{Binding RuqyaName}" RelativePanel.AlignLeftWithPanel="True" VerticalAlignment="Center" Margin="15,15,0,0" HorizontalAlignment="Center"/> 
        <StackPanel Orientation="Horizontal" RelativePanel.AlignRightWithPanel="True" Padding="0,0,20,0" RelativePanel.RightOf="lblVerseName" HorizontalAlignment="Right"> 
         <TextBlock x:Uid="lblRepeatNum" x:Name="lblRepeatNum" Text="{Binding NumOfTimes}" HorizontalAlignment="Right" Margin="0,0,20,0" VerticalAlignment="Center"/> 
         <Button x:Name="btnIncrement" Width="35" Height="35" Tag="{Binding index}" Click="btnIncrement_Click" Content="+" Margin="0,0,10,0"/> 
         <Button x:Name="btnDecrement" Width="35" Height="35" Tag="{Binding index}" Click="btnDecrement_Click" Content="-"/> 
        </StackPanel> 
       </RelativePanel> 

      </DataTemplate> 
     </ListView.ItemTemplate> 

    </ListView> 

private void btnDecrement_Click(object sender, RoutedEventArgs e) 
    { 

     //get index of selected row 
     int index = (int)((Button)sender).Tag; 

     //get object at this index 
     Ruqya rq = (Ruqya) lvBuildYourRuqya.Items[index]; 

     //decrement 
     rq.NumOfTimes -= 1; 

     //update lblRepeatNum 
     ???????? 
    } 
+0

'NumOfTimes'是否實現了'INotifyPropertyChanged'? –

+0

嘗試使用綁定 – lindexi

回答

1

由於賈斯汀XL說,你需要實現I​Notify​Property​Changed接口你想動態改變的屬性。因此,一旦NumOfTimes由代碼行rq.NumOfTimes -= 1;更改,lblRepeatNum將自動更改。例如,你的Ruqya類可以繼承I​Notify​Property​Changed如下:

public class Ruqya : INotifyPropertyChanged 
{ 
    private int _numOfTimes; 
    public int NumOfTimes 
    { 
     get 
     { 
      return _numOfTimes; 
     } 

     set 
     { 
      this._numOfTimes = value; 
      this.OnPropertyChanged(); 
     } 
    } 
    public string RuqyaName { get; set; } 
    public int index { get; set; } 

    public event PropertyChangedEventHandler PropertyChanged =delegate { }; 

    public void OnPropertyChanged([CallerMemberName] string propertyName = null) 
    { 
     // Raise the PropertyChanged event, passing the name of the property whose value has changed. 
     this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
    } 
} 

更多細節請參考Data binding in depth。 對於您的場景我也推薦您使用I​Command界面進行按鈕點擊事件處理,更多細節請參考this sample

+0

謝謝!我是UWP的新手,會閱讀更多關於綁定的內容。 –