1

I have a WPF form set up as follows;

<ListBox x:Name="lbModules" HorizontalAlignment="Stretch" Margin="0,0,0,0" VerticalAlignment="Stretch">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Button Command="{Binding OnClick}">
                <StackPanel>
                    <Image Source="{Binding ModuleIcon}"/>
                    <Label Content="{Binding ModuleName}"/>
                </StackPanel>
            </Button>
        </DataTemplate>
    </ListBox.ItemTemplate>
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel></WrapPanel>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</ListBox>

In the code behind, lbModules is given a List<ModuleButton> as the ItemsSource, where ModuleButton is defined as follows;

internal class ModuleButton
{
    public ImageSource ModuleIcon {get; set;}
    public string ModuleName {get; set;}
    public ICommand OnClick {get; set;}
}

My problem is defining the OnClick command in a dynamic fashion. I need to do this as I am using MEF and the OnClick event is technically in a different assembly. I just need to call module.GetForm() but it doesn't seem to be quite that simple...

I build the ModuleButton(s) as follows;

Lazy<IModule, IModuleMetadata> moduleCopy = module;
ModuleButton button = new ModuleButton
{
    ModuleName = moduleCopy.Metadata.ModuleName,
    ModuleIcon = 
        Imaging.CreateBitmapSourceFromHBitmap(moduleCopy.Value.ModuleButtonIcon.GetHbitmap(),
            IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()),
    OnClick = // TODO: Somehow call moduleCopy.Value.GetForm()
};

I've been searching far and wide, checking various results in Google, this is one of my latest sources.

Is it possible to do what I'm trying to do? If so, how?

1 Answer 1

3

OK, try my version since Patrick's answer does not implement ICommand's CanExecuteChanged event so you can't compile smoothly; Also, this RelayCommand has overloaded 'ctor that takes only one parameter- CanExecute always returning true - makes it easier to use.

It is taken from MSDN magazine article WPF Apps With The Model-View-ViewModel Design Pattern.

public class RelayCommand : ICommand
{
    #region Fields

    readonly Action<object> _execute;
    readonly Predicate<object> _canExecute;

    #endregion // Fields

    #region Constructors

    /// <summary>
    /// Creates a new command that can always execute.
    /// </summary>
    /// <param name="execute">The execution logic.</param>
    public RelayCommand(Action<object> execute)
        : this(execute, null)
    {
    }

    /// <summary>
    /// Creates a new command.
    /// </summary>
    /// <param name="execute">The execution logic.</param>
    /// <param name="canExecute">The execution status logic.</param>
    public RelayCommand(Action<object> execute, Predicate<object> canExecute)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");

        _execute = execute;
        _canExecute = canExecute;
    }

    #endregion // Constructors

    #region ICommand Members

    [DebuggerStepThrough]
    public bool CanExecute(object parameter)
    {
        return _canExecute == null ? true : _canExecute(parameter);
    }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public void Execute(object parameter)
    {
        _execute(parameter);
    }

    #endregion // ICommand Members
}

and

OnClick = new RelayCommand ((o) => 
    {
        moduleCopy.Value.GetForm();
    });
Sign up to request clarification or add additional context in comments.

2 Comments

more complete answer. I will delete mine. (+1)
Awesome, that works just like I was hoping for and I can even expand the anonymous method. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.