gpt4 book ai didi

c# - 在带有用户控件的主窗口中使用 RoutedCommand

转载 作者:太空宇宙 更新时间:2023-11-03 12:32:12 29 4
gpt4 key购买 nike

我想了解路由命令的工作原理,但我遇到了问题。我创建了一个带有 Button 的主窗口和带有 UserControls 的 ItemControl 作为其 Item 模板。

<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 绑定(bind)到 RoutedCommand。

<UserControl.CommandBindings>
<CommandBinding Command="{x:Static helpers:RoutedCommands.SendChangesCommand}"
Executed="CommandBinding_Executed"/>

代码隐藏中的方法:

private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
// Do something
}

我以为当我单击按钮时它会在每个用户控件对象上触发方法,但遗憾的是这段代码不起作用 - 按钮被禁用。我错过了什么?

最佳答案

Thought It will fire method on every User Control object when I click the button, but sadly this code doesn't work - button is disabled. What am I missing?

RoutedCommand 从目标元素搜索可视树,即调用命令的元素,在本例中是您的 Button,并查找在其 CommandBindings 集合中具有匹配的 CommandBinding 对象的元素,然后为这个特定的 CommandBinding< 执行 Execute 委托(delegate).

这里的问题是 ItemsControl 中的 UserControl 元素不是 Button 的可视父元素,因此永远不会调用该命令。

如果将 CommandBinding 移动到父 Grid 中,将启用 Button:

<Grid>
<Grid.CommandBindings>
<CommandBinding Command="{x:Static local:RoutedCommands.SendChangesCommand}"
Executed="CommandBinding_Executed"/>
</Grid.CommandBindings>
<ItemsControl
...

如果您真的想在单击 Button 时对 UserControls 执行某些操作,则使用 RoutedCommand 不是执行此操作的方法.

相反,您应该查看 MVVM design pattern以及如何实现您的自定义 ICommand 或使用任何 MVVM 库中的通用实现。这是另一个故事,但请参阅以下博客文章进行简要介绍:https://blog.magnusmontin.net/2013/06/30/handling-events-in-an-mvvm-wpf-application/ .

MVVM 是在构建基于 XAML 的应用程序时推荐使用的设计模式,所有认真的 WPF 开发人员都应该学习它。

关于c# - 在带有用户控件的主窗口中使用 RoutedCommand,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42316946/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com