我有一个ItemsControl控件,它有一个ObservableCollection作为其ItemsSource.它还有一个位于DataTemplate内部的按钮.按钮的Command属性绑定到ViewModel中的RelayCommand(我使用的是MVVM Light),CommandParameter绑定到ItemsSource中的相应项.
问题是由于某种原因,命令永远不会触发.另一方面,代码隐藏工作正常.调试鼠标单击事件处理程序时,我可以看到发送方(类型为Button)的CommandParameter填充了正确的数据,而Command为null.
我在这里想念的是什么?
XAML:
<ItemsControl ItemsSource="{Binding Users}"
Margin="{StaticResource ContentMargin}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Margin="{StaticResource ImageButtonMargin}"
Style="{StaticResource ImageButtonStyle}"
Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}, Path=DataContext.UserSelectedCommand}"
CommandParameter="{Binding}">
<!--...-->
Run Code Online (Sandbox Code Playgroud)
视图模型:
private ObservableCollection<User> _users;
private RelayCommand<User> _userSelectedCommand;
public ObservableCollection<User> Users
{
get { return _users; }
set
{
_users = value;
RaisePropertyChanged();
}
}
public RelayCommand<User> UserSelectedCommand
{
get { return _userSelectedCommand; }
}
protected override sealed void SetCommands() // called in the constructor which is in turned called by SimpleIoc
{
userSelectedCommand = new RelayCommand<User>((user) => UserSeriesSelected(user));
}
private void UserSelected(User selectedUser)
{
}
Run Code Online (Sandbox Code Playgroud)
loo*_*ode 12
使用命名元素绑定作为数据模板内的绑定源,以从根数据上下文访问命令.您可以使用根网格或其他容器作为命名元素.ItemsControl iteself也可以使用.
<ItemsControl x:Name="MyItems" ItemsSource="{Binding Users}"
Margin="{StaticResource ContentMargin}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Margin="{StaticResource ImageButtonMargin}"
Style="{StaticResource ImageButtonStyle}"
Command="{Binding ElementName=MyItems, Path=DataContext.UserSelectedCommand}"
CommandParameter="{Binding}">
<!--...-->
Run Code Online (Sandbox Code Playgroud)
您需要将“FindAncestor”添加到相对源绑定中:RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}
| 归档时间: |
|
| 查看次数: |
7732 次 |
| 最近记录: |