我需要更新用于在运行时加载listview的DataTemplate中的文本块。每次用户单击“递增”或“递减”按钮时,必须相应地增加或减少lblRepeatNum。
我很难从按钮的click事件中访问文本块。请帮忙。
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 :(得分:1)
正如Justin XL所说,您需要为要动态更改的属性实现INotifyPropertyChanged
接口。因此,一旦NumOfTimes
由代码行rq.NumOfTimes -= 1;
更改,lblRepeatNum
将自动更改。例如,您的Ruqya
类可以继承INotifyPropertyChanged
,如下所示:
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。
对于您的场景,我还建议您使用ICommand
界面来显示按钮点击事件句柄,有关详细信息,请参阅this sample。