【发布时间】:2017-02-18 15:17:37
【问题描述】:
我正在尝试了解路由命令的工作原理,但我遇到了一个问题。我创建了一个主窗口,其中包含 Button 和 ItemControl,并以 UserControls 作为其项目模板。
<Window>
<Grid>
<ItemsControl
ItemsSource="{Binding CollectionOfUsers}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<uc:UserUserControl
Name="{Binding PersonName}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
<Button
Command="{x:Static helpers:RoutedCommands.SendChangesCommand}"
Content="SAVE"/>
</Grid>
</Window>
如果单击主窗口中的按钮,我想从 ItemsControl 中的每个 UserControl 运行一些方法。
我在静态类中创建了 RoutedCommand:
public static class RoutedCommands
{
public static readonly RoutedCommand SendChangesCommand = new RoutedCommand();
}
并将 UserControl 绑定到 RoutedCommand。
<UserControl.CommandBindings>
<CommandBinding Command="{x:Static helpers:RoutedCommands.SendChangesCommand}"
Executed="CommandBinding_Executed"/>
在代码隐藏中使用方法:
private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
// Do something
}
Thought 当我单击按钮时,它会在每个用户控件对象上触发方法,但遗憾的是这段代码不起作用 - 按钮被禁用。我错过了什么?
【问题讨论】:
标签: c# wpf user-controls routed-commands