WPF列表视图/数据网格内的按钮 [英] Button inside a WPF List view/data grid
问题描述
我正在尝试获取所单击行的值/ID.如果选择了该行,则可以正常工作.但是,如果我只是尝试单击其中的按钮,则所选客户为空.如何在此处执行命令参数.
我试着看到以下问题的答案:
I am trying to get the value/ID of the clicked row. If the row is selected, this works fine. But if I just try to click the button inside, the selected customer is null. How do I do Command Parameters here.
I tried this see the answers to the following questions:
这是代码:
<Grid>
<ListView ItemsSource="{Binding Path=Customers}"
SelectedItem="{Binding Path=SelectedCustomer}"
Width="Auto">
<ListView.View>
<GridView>
<GridViewColumn Header="First Name">
<GridViewColumn.CellTemplate>
<DataTemplate>
<StackPanel Margin="6,2,6,2">
<TextBlock Text="{Binding Name}"/>
</StackPanel>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Address">
<GridViewColumn.CellTemplate>
<DataTemplate>
<StackPanel Margin="6,2,6,2">
<Button Content="Address" Command="{Binding Path=DataContext.RunCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}"/>
</StackPanel>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</Grid>
public class VM : ViewModelBase
{
public RelayCommand RunCommand { get; private set; }
private ObservableCollection<Customer> _Customers;
public ObservableCollection<Customer> Customers
{
get { return _Customers; }
set
{
if (value != _Customers)
{
_Customers = value;
RaisePropertyChanged("Customers");
}
}
}
private Customer _SelectedCustomer;
public Customer SelectedCustomer
{
get { return _SelectedCustomer; }
set
{
if (value != _SelectedCustomer)
{
_SelectedCustomer = value;
RaisePropertyChanged("SelectedCustomer");
}
}
}
public VM()
{
Customers = Customer.GetCustomers();
RunCommand = new RelayCommand(OnRun);
}
private void OnRun()
{
Customer s = SelectedCustomer;
}
}
在OnRun方法中,选定的Customer输入为null.我想要这里的数据行(客户).我该怎么做?
in the OnRun Method, selected Customer is coming in as null. I want the data row(customer) here. How do I do this?
推荐答案
您可以选择三种可能的解决方案.
Three possible solutions that you can choose.
- 将当前行对象作为CommandParameter传递.在这种情况下,您将稍微修改OnRun方法. (推荐)
<Button Content="Address" Command="{Binding Path=DataContext.RunCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}" CommandParameter={Binding} />
我认为 CommandParameter = {Binding} 可以正常工作,因为每一行的DataContext是每个Customer对象.
I think CommandParameter={Binding} works fine because the DataContext of each row is each Customer object.
和OnRun方法需要修改才能获取参数作为参数.
and OnRun method needs to be modified in order to get a parameter as an argument.
private void OnRun(object o){
if(!(o is Customer)) return;
// Do something
}
-
或者,使用SelectionChanged事件处理编写一些代码. (不推荐)
Or, Write a little code-behind with SelectionChanged event handling. (not recommended)
或者,在MVVM-light工具箱中使用EventToCommand. (不推荐)
Or, Use EventToCommand in MVVM-light toolkit. (not recommended)
这篇关于WPF列表视图/数据网格内的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!