【问题标题】:Passing a value along from a Button in a WPF ListView从 WPF ListView 中的按钮传递值
【发布时间】:2010-10-01 16:17:48
【问题描述】:

我有一个在 WPF 列表视图中显示的集合。我将在每一行中都有一个编辑按钮,并且需要在单击该按钮时将一个 ID 传递给屏幕上的另一个控件。我不会在原地进行编辑,所以我不会使用 Gridview。

如何将此 ID 传递给我的其他控件?

目前我的 XAML 看起来像这样。

<ListView Name="uxPackageGroups" ItemsSource="{Binding PackageGroups}" BorderThickness="0" Grid.Row="6" Grid.Column="1" Width="300" BorderBrush="#FF0000E8">
<ListView.ItemTemplate>
    <DataTemplate>
        <StackPanel Name="uxStackPanel" Orientation="Horizontal">
            <Button Content="Edit" Width="50" />
            <Label Content="{Binding Name}" Height="20" Margin="0" Padding="0"/>
        </StackPanel>
    </DataTemplate>
</ListView.ItemTemplate>

这位 WPF 新手提前感谢您!

【问题讨论】:

  • 有关此问题的更多信息,请参阅下面的“答案”。谢谢!

标签: wpf xaml listview


【解决方案1】:

您正在使用数据绑定,因此非常简单。在响应按钮单击的代码中,获取对按钮的引用并检查其 DataContext 属性。这将引用您绑定到的基础对象。

protected void EditButton_Click(object sender, RoutedEventArgs e)
{
   TextBox textBox = (TextBox)sender;

   int id =  ((TheBounObjectType)textBox.DataContext).Id;
}

【讨论】:

    【解决方案2】:

    如果您不想创建命令来执行此操作,可以使用按钮的“标签”属性:

    <Button Content="Edit" Width="50" Tag={Binding} />
    

    <Button Content="Edit" Width="50" Tag={Binding ID} />
    

    然后在您的事件处理程序中引用按钮的标记属性。

    【讨论】:

      【解决方案3】:

      命令参数对此有好处:

       <Button Content="Edit" Width="50" 
            Command="{some command here}" 
            CommandParameter="{Binding ID}" />
      

      对于“此处的某些命令”部分,请确保您是 declaring a command

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-15
        • 1970-01-01
        • 1970-01-01
        • 2017-07-29
        相关资源
        最近更新 更多