I am working on a WPF where I need to dynamically generate Togglebutton 16 times. It will be inefficient if I write down this Togglebutton 16 times and have individual Button Click Command for them.
XAML:
<Togglebutton Height="14" Command="{Binding TogglebuttonGen}" Margin="0" Name="checkBox1" Grid.Column="0" VerticalAlignment="Center" HorizontalAlignment="Center" />
I would ideally want to generate them 16 times and have one common method in my viewmodel class as follows:
private ICommand mTogglebuttonGen;
public ICommand TogglebuttonGen
{
get
{
if (mTogglebuttonGen == null)
mTogglebuttonGen = new DelegateCommand(new Action(mTogglebuttonGenExecuted), new Func<bool>(mTogglebuttonGenCanExecute));
return mTogglebuttonGen;
}
set
{
mTogglebuttonGen = value;
}
}
public bool mTogglebuttonGenCanExecute()
{
return true;
}
public void mTogglebuttonGenExecuted(some INDEX parameter which gives me selected Togglebutton)
{
// Have a common method here which performs operation on each Togglebutton click based on INDEX which determines which Togglebutton I have selected
}
I had done it in my C++ app as follows:
for(int j = 0; j < 16; j ++)
{
m_buttonActiveChannels[j] = new ToggleButton();
addAndMakeVisible(m_buttonActiveChannels[j]);
m_buttonActiveChannels[j]->addButtonListener(this);
}
//Checking which Togglebutton is clicked
unsigned bit = 0x8000;
for(int i = 15; i >= 0; i--)
{
if(0 != (value & bit)) //Value has some hardcoded data
{
m_buttonActiveChannels[i]->setToggleState(true);
}
else
{
m_buttonActiveChannels[i]->setToggleState(false);
}
bit >>= 1;
}
Hence this generates it 16 times and has one method which performs operation based on index i.
How can I achieve it in my wpf app? 🙂
In your viewmodel, create a collection with 16 instances of your ToggleAction class.
Bind this collection to the ItemsSource of a ItemsControl, and that’s it.
This is all handwritten, so check for errors. What’s most important is the command binding. If you want to call the command from your ViewModel, you have to use RelativeSource to walk up to the ViewModel DataContext.
I would also handle/bind the toggle state in MyToggleActionClass.