Reputation: 1
I need to update a textblock within a DataTemplate used to load a listview at runtime. Each time the user clicks on the Increment or Decrement button, the lblRepeatNum has to be incremented or decremented accordingly.
I am having a hard time to access the textblock from inside the click event of the buttons. Please help.
XAML & c# code below.
<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
????????
}
Upvotes: 0
Views: 378
Reputation: 10627
As Justin XL said, you need to implement INotifyPropertyChanged
interface for the property you want to dynamic changed. So that once the NumOfTimes
changed by code line rq.NumOfTimes -= 1;
the lblRepeatNum
will be changed automatically. For example, your Ruqya
class could inherit the INotifyPropertyChanged
as follows:
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));
}
}
More details please reference Data binding in depth.
For your scenario I also recommend you use ICommand
interface for the button click event handles, more details about this please reference this sample.
Upvotes: 1