我正在尝试获取所点击行的值/ ID。如果选择该行,这可以正常工作。但是,如果我只是尝试单击内部按钮,则所选客户为空。我在这里怎么做命令参数 我试过这个看到以下问题的答案:
ListView and Buttons inside ListView
以下是代码:
<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;
}
}
答案 0 :(得分:9)
您可以选择三种可能的解决方案。
<Button Content="Address" Command="{Binding Path=DataContext.RunCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}" CommandParameter={Binding} />
我认为 CommandParameter = {Binding} 可以正常工作,因为每行的DataContext都是每个Customer对象。
需要修改和OnRun方法才能将参数作为参数。
private void OnRun(object o){ if(!(o is Customer)) return; // Do something }
或者,使用SelectionChanged事件处理编写一些代码隐藏。 (不推荐)
或者,在MVVM-light工具包中使用EventToCommand。 (不推荐)
答案 1 :(得分:0)