简体   繁体   中英

Add Click Event To Button Template?

I am writing a WPF app, and need to be able to bind a method call with arguments to a button's Click event (or equivalent).

Until now, just for testing I was programmatically creating the buttons and setting them as children of the necessary StackPanel.

foreach (Page p in pages)
        {
            Button newTestBtn = new Button();
            newTestBtn.Content = p.Title;
            newTestBtn.Name = p.Name.Replace(" ", string.Empty);
            newTestBtn.FontSize = 14;
            newTestBtn.Margin = new Thickness(2, 0, 2, 2);
            newTestBtn.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FF414141"));
            newTestBtn.Click += (s, e) => { SwitchPage(p); };

            hp.CreateNewTestEntry(newTestBtn);
        }

After deciding this was far from the best way of doing this, I set up a more permanent solution by having an ItemsControl bound to an ObservableCollection of a serialized class.

I have hit a new problem though, applying an ICommand or RoutedEventArg to a Click or Command on a button simply doesn't seem to work.

foreach (Page p in pages)
        {
            TempCl tcl = new TempCl();
            tcl.ToolName = p.Title;
            tcl.TriggerEvent = SwitchPage(p);

            tempHolder.Add(tcl);
        }

Google & StackOverflow searching hasn't yielded any easy ways of doing this and I'm a bit stuck.

<Button Margin="0, 0, 0, 2" Content="{Binding ToolName}" Command="{Binding TriggerEvent}" FontSize="14" Background="#FF414141"/>

Does anyone know the correct way of doing this without adding a lengthy class to do this? There must be an elegant solution.

First, if You want a more maintainable app in the future, you have to start by studying the basics of MVVM approach. Basically, your code can be separated into 3 different stuff: Model - ViewModel - View.

As it was mentioned in the comments to your question, it is required to bind Command dependency property of a Button to a property of ICommand type in your ViewModel (that should be a DataContext for your View or your Control, etc) and specify CommandParameter as well (it will be passed to the Command).

Generic ICommand implementation (eg DelegateCommand<T> or RelayCommand<T> ) allows you to specify the parameter, which in your case might be whatever you like that describes the target of navigation).

You can find a more detailed sample with Page navigation HERE .

Also, it might be useful for you to figure out and use Prism Library . It provides a lot of functionality around modularity, Views navigation in a single Window, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM