我一直在试图弄清楚如何从Loaded=""
事件。我在这里问了一个问题:我将如何在 Loaded=" " 上传递参数? https://stackoverflow.com/questions/30488770/how-would-i-go-about-passing-a-parameter-on-loaded并被引导向 InvokeCommandAction 的方向。
问题是我无法弄清楚如何实际使用 InvokeCommandAction 来调用我的方法。我的 XAML:
<Expander x:Name="Greeting_And_Opening_Expander" ExpandDirection="Down" IsExpanded="True" FontSize="14" FontWeight="Bold" Margin="5" BorderThickness="1" BorderBrush="#FF3E3D3D">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding ExpanderLoaded}"
CommandParameter="x:Static local:Sections.Opening"/>
</i:EventTrigger>
</i:Interaction.Triggers>
我有一个名为ExpanderLoaded
背后的代码如下:
private void ExpanderLoaded(object sender, RoutedEventArgs e, Sections section)
{
//Do Stuff
}
以及同一命名空间下的枚举:
public enum Sections
{
Default = 0,
Opening = 1,
Verify = 2
}
我需要做什么才能使用上面发布的 XAML 调用我的方法?我对 WPF 非常陌生,所以如果我最终提出了一些看似愚蠢的问题,请耐心等待。我浏览过 stackoverflow 阅读其他类似的问题,但无法找到足够的信息来继续我自己的工作。
命令绑定需要一个实现 ICommand 接口的具体实例。您正在绑定到一个方法名称,它根本不会真正绑定。命令绑定旨在在 MVVM 设计中的 ViewModel 类中使用,但从您的示例代码来看,您似乎在 Xaml 视图的代码隐藏中使用它。如果您想坚持使用代码隐藏,只需使用事件处理程序。
有很多关于 ICommand 实现的示例,您也可以开箱即用委托命令 https://msdn.microsoft.com/en-us/library/gg431410%28v=pandp.50%29.aspx可用于Prism https://msdn.microsoft.com/en-us/library/gg406140.aspx。我在下面展示了一个简单的示例,它实现了一个非常基本的 ICommand,只要您的 View 和 ViewModel 连接起来,它就可以满足您想要执行的操作。
//Very basic ICommand implementation
public class RelayCommand : ICommand
{
private Action<object> command;
private Func<bool> canExecute;
public RelayCommand(Action<object> commandAction, Func<bool> canExecute = null)
{
this.command = commandAction;
this.canExecute = canExecute;
}
/// <summary>
/// Returns default true.
/// Customize to implement can execute logic.
/// </summary>
public bool CanExecute(object parameter)
{
return this.canExecute == null ? true : this.canExecute();
}
/// <summary>
/// Implement changed logic if needed
/// </summary>
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
if (this.command != null)
{
this.command(parameter);
}
}
}
//Example of a view model
public class MyViewModel
{
public MyViewModel()
{
this.ExpanderCommand = new RelayCommand(this.ExecuteExpanderCommand);
}
// This property will be the command binding target
public RelayCommand ExpanderCommand { get; set; }
// this is the handler method
public void ExecuteExpanderCommand(object parameter)
{
var section = (Sections)parameter;
//do your stuff here
}
}
Xaml 绑定:
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding ExpanderCommand}"
CommandParameter="x:Static local:Sections.Opening"/>
</i:EventTrigger>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)