gpt4 book ai didi

WPF:使用在 UserControl 中绑定(bind)的命令

转载 作者:行者123 更新时间:2023-12-01 11:57:13 25 4
gpt4 key购买 nike

我正在使用 MVVM 做一个示例,但遇到命令问题。我有一个文章类(带有 ID、名称、价格等)、一个表示 View 模型的 ArticleViewModel 和一个允许输入文章数据的用户控件 (ArticleControl),并绑定(bind)到 ArticleViewModel 的属性.此用户控件正在竞标保存命令。

   <UserControl.CommandBindings>
<CommandBinding x:Name="saveCmd"
Command="local:Commands.Save"
CanExecute="CommandBinding_CanExecute"
Executed="CommandBinding_Executed"/>
</UserControl.CommandBindings>

命令是这样定义的:

   public class Commands
{
private static RoutedUICommand _save;
public static RoutedUICommand Save
{
get { return _save; }
}

static Commands()
{
InputGestureCollection saveInputs = new InputGestureCollection();
saveInputs.Add(new KeyGesture(Key.S, ModifierKeys.Control, "Ctrl+S"));

_save = new RoutedUICommand(
"Save",
"Save",
typeof(Commands),
saveInputs);
}
}

以及命令绑定(bind)处理程序:

  private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
double baseprice = 0;
double.TryParse(ArticleBasePrice.Text, out baseprice);

e.CanExecute =
!string.IsNullOrEmpty(ArticleID.Text) &&
!string.IsNullOrEmpty(ArticleName.Text) &&
!string.IsNullOrEmpty(ArticleDescription.Text) &&
baseprice > 0;
}

private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
ArticleViewModel avm = (ArticleViewModel)DataContext;
if (avm != null && avm.Save())
{
ArticleID.Text = String.Empty;
ArticleName.Text = String.Empty;
ArticleDescription.Text = String.Empty;
ArticleBasePrice.Text = String.Empty;
}
}

现在,我将这个用户控件放在一个窗口上。当我按下 Ctrl+S 时,命令被执行。但是,我还在那个窗口上放了一个保存按钮,就在这个用户控件旁边。当我单击它时,我想执行相同的命令(并且我不想在托管用户控件的窗口中执行另一个命令绑定(bind))。

   <StackPanel>
<local:ArticleControl x:Name="articleControl" />
<Button Name="btnSave"
Content="Save" Width="100"
HorizontalAlignment="Left"
Command="{???}"/> <!-- what should I put here? -->
</StackPanel>

但我不知道如何引用用户控件中定义的 saveCmd。我尝试了不同的东西,有些是完全错误的(它们在运行应用程序时抛出异常),有些没有任何效果。

Command="{StaticResource saveCmd}"
Command="{StaticResource local:ArticleControl.saveCmd}"
Command="{x:Static local:Commands.Save}"

感谢任何帮助。谢谢。

最佳答案

保存按钮不会导致其他控件的命令绑定(bind)执行的原因是因为保存按钮在用户控件之外,因此命令系统不会在该控件中查找命令绑定(bind)。 Command 执行策略有点像冒泡事件,将从焦点项(Button)开始,沿着可视化树向上移动,直到找到 CommandBindings。

您可以在父控件中实现命令绑定(bind),也可以将保存按钮的 CommandTarget 属性设置到用户控件。

另一种方法是在按钮或按钮的容器上设置 FocusManager.IsFocusScope=True。如果你这样做,我建议你阅读一下 IsFocusScope 的作用,但简而言之,当你按下按钮时,它将把输入焦点留在任何有焦点的控件上,而不是让按钮成为新的输入重点。这通常用于工具栏或类似菜单的结构。

关于WPF:使用在 UserControl 中绑定(bind)的命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5884643/

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