gpt4 book ai didi

c# - CallMethodAction 绑定(bind)到 Button 失败

转载 作者:行者123 更新时间:2023-12-03 10:43:02 25 4
gpt4 key购买 nike

没有错误。我正在尝试学习 MVVM。设置很简单。单击按钮时我没有得到任何输出。 Xaml 应该没问题,因为我已经通过将行为拖动到按钮来在 Blend 中生成交互部分。注意:我打算使用方法,而不是命令,因为命令仅涵盖单击,但不包括 DoubleClick。

<Window
x:Class="MVVM_1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:local="clr-namespace:MVVM_1"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="525"
Height="350"
mc:Ignorable="d"
>
<Window.DataContext>
<local:ViewModel/>
</Window.DataContext>
<Grid>
<Button x:Name="button"
Width="75"
Margin="198,168,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Content="TestMethod">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseLeftButtonDown" SourceName="button">
<ei:CallMethodAction MethodName="MethodTesting"
TargetObject="{Binding}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</Grid>
using System.Windows;

namespace MVVM_1
{
public class ViewModel
{

public static void MethodTesting()
{
MessageBox.Show("Success!");
}
}
}

最佳答案

您需要使用命令将控件绑定(bind)到单击事件。

MVVM - Commands, RelayCommands and EventToCommand

代替:

public static void MethodTesting()  
{
MessageBox.Show("Success!");
}

使用 this example :
public ICommand ButtonClickCommand 
{
get { return new DelegateCommand<object>(FuncToCall, FuncToEvaluate);}
}

private void FuncToCall(object context)
{
//this is called when the button is clicked
MessageBox.Show("Success!");
}

private bool FuncToEvaluate(object context)
{
//this is called to evaluate whether FuncToCall can be called
//for example you can return true or false based on some validation logic
return true;
}

也在这个 How do you create an OnClick command in WPF MVVM with a programmatically created button?下- is another great example .

关于c# - CallMethodAction 绑定(bind)到 Button 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45301163/

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