2017-06-27 31 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的新手,会阅读更多关于绑定的内容。 –