【发布时间】:2018-07-18 19:09:07
【问题描述】:
我正在尝试在 UWP 中做一些基本的 UI 和绑定以使我的头脑清醒,但我无法访问列表视图项中的按钮。
我有一个按钮,点击它时,它会创建一个新对象,该对象将添加到我的 ObservableCollection 中,然后最终在我的 ListView 中添加一个新项目
XMAL
<ListView Grid.Row="1" ItemsSource="{x:Bind counts}" x:Name="buttonsView" Margin="5,0" Background="White" Foreground="#FF5059AB">
<ListView.ItemTemplate>
<DataTemplate x:DataType="local:Counter">
<StackPanel Orientation="Vertical">
<TextBlock Text="{x:Bind CountValue, Mode=TwoWay}" FontWeight="Black"/>
<Button Click="Increment_Click" Content="Increment"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
C#
public class Counter
{
private int count;
public Counter()
{
count = 0;
}
public int CountValue
{
get
{
return count;
}
set
{
count = value;
}
}
}
public sealed partial class MainPage : Page
{
ObservableCollection<Counter> counts = new ObservableCollection<Counter>();
public MainPage()
{
this.InitializeComponent();
}
private void Increment_Click(object sender, RoutedEventArgs e)
{
// ?
}
private void AddCounter_Click(object sender, RoutedEventArgs e)
{
counts.Add(new Counter());
}
}
这行得通。
但是当我单击 StackPanel 中的按钮时,会调用 Increment_Click 方法,但我不确定此时该做什么。我想通过获取 ListView 项的索引并使用它来索引 ObservableCollection 来访问 Counter 对象。
如何确定添加的 ListView 项的索引是什么?
【问题讨论】: