StonedJesus
StonedJesus

Reputation: 397

Control Failing To Enter The Method when Dynamically generated Buttons are clicked in WPF

I am sorry for weird title. I am dealing with dynamic generation of Ui components. I have a ListBox in my Xaml class which generates the buttons dynamically.

View:

<ListBox x:Name="SetButtonList" ItemsSource="{Binding}" >
         <ListBox.ItemTemplate>
               <DataTemplate >
                     <Grid>                                   
                         <Button Content="{Binding Path=SetButtonFreq}" Command="{Binding Path=SetFreqCommand}" />                                    
                     </Grid>
               </DataTemplate>
         </ListBox.ItemTemplate>
</ListBox>

ViewModel:

private ICommand mSetFreqCommand;
public ICommand SetFreqCommand
    {
        get
        {
            if (mSetFreqCommand == null)
                mSetFreqCommand = new DelegateCommand(new Action(SetFreqCommandExecuted), new Func<bool>(SetFreqCommandCanExecute));

            return mSetFreqCommand;
        }
        set;            
    }

    public bool SetFreqCommandCanExecute()
    {
        return true;
    }

    public void SetFreqCommandExecuted()
    {
        // Executes the Body when Button is Clicked
    }

Model:

private string _SetFreqValue = "";
public String SetButtonFreq
    {
        set; get;            
    }

    public ClockModel(string SetButtonFreq)
    {
        this.SetButtonFreq = SetButtonFreq;
    }        

    public override string ToString()
    {
        return _SetFreqValue;
    }

View.cs file:

// mClock is object of Model Class
mClock.Add(new ClockModel("Set 12.0 MHz"));
mClock.Add(new ClockModel("Set 12.288 MHz"));
mClock.Add(new ClockModel("Set 15.36 MHz"));
mClock.Add(new ClockModel("Set 19.2 MHz"));            

This gives me 4 buttons with different frequencies in my listbox. But when I try to Click them the control doesn't enter the SetFreqCommandExecuted() method. Where am i making a mistake? :(

Please help

Upvotes: 1

Views: 69

Answers (1)

EgorBo
EgorBo

Reputation: 6152

The button tries to find SetFreqCommand inside the bound item, not in your general ViewModel for current page. You may fix it with this binding:

Command="{Binding ElementName=SetButtonList, Path=DataContext.SetFreqCommand}"

Upvotes: 2

Related Questions