在 GridViewColumn 按钮的单击事件处理程序中获取绑定项

Get bound item inside click event handler of the GridViewColumn button

我正在尝试制作一个显示星期几和 start/end 工作日的应用程序作为练习。

所以我用这些元素和绑定制作了 XAML:

<StackPanel Grid.Row="1" Margin="0,0,0,0" >
            <ListView ItemsSource="{Binding TimeListView}">
                <ListView.View>
                    <GridView>
                        <GridViewColumn Width="200" Header="Day" 
                    DisplayMemberBinding="{Binding Date}"  />
                        <GridViewColumn Width="200" Header="Time"  
                    DisplayMemberBinding="{Binding Time}" />
                        <GridViewColumn Width="50">
                            <GridViewColumn.CellTemplate>
                                <DataTemplate>
                                    <Button x:Name="EditEntry" Content="Edit" Click="EditClick" />
                                </DataTemplate>
                            </GridViewColumn.CellTemplate>
                        </GridViewColumn>
                    </GridView>
                </ListView.View>
            </ListView>
        </StackPanel>

在我的 EditClick 中我有这个代码:

private void EditClick(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Sender: " + sender.ToString());
}

所以我的问题是:如何在我的 EditClick 函数的同一行中获取日期和时间的数据?

好的,如果我对问题的解释正确,当调用 EditClick 函数时,您想获取当前选择的日期和时间吗?

如果是这样,就这样做:

string theCurrentSelectedDateTime = YouListView.ColumnOne.SelectedItem.ToString() + YourListView.ColumnTwo.SelectedItem.ToString();

这应该可以满足您的需求。但是,如果您要问其他问题,请发表评论,因为我还不允许发表评论:(.

最简单的方法是使用 DataContext property of the sender button. It will contain the item bound to the current("parent") 行:

public MainWindow()
{
    InitializeComponent();

    this.TimeListView = new ObservableCollection<Item>(new Item[]
        {
            new Item(),
            new Item()
        });

    this.DataContext = this;
}

public ObservableCollection<Item> TimeListView
{
    get;
    private set;
}

private void EditClick(object sender, RoutedEventArgs e)
{
    var button = (Button)sender;

    var item = (Item)button.DataContext;

    MessageBox.Show("Item is: " + item.ToString());
}

项目class:

public class Item
{
    public Item()
    {
        this.Day = DateTime.Now.DayOfWeek;
        this.Time = DateTime.Now.TimeOfDay;
    }

    public DayOfWeek Day { get; set; }

    public TimeSpan Time { get; set; }

    public override string ToString()
    {
        return String.Format("{0}, {1}", this.Day, this.Time);
    }
}