【发布时间】:2012-10-18 14:58:07
【问题描述】:
我是一名 C++ 开发人员,最近转向 C#。我在我的 wpf 应用程序中使用 MVVM 模式。我正在研究单选按钮的动态生成。好吧,这个要求很简单,我需要生成 24 个单选按钮,这样一次只检查一个单选按钮。代码如下:
XAML:
<Grid Grid.Row="1">
<GroupBox Header="Daughter Cards" >
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition Width="220" />
</Grid.ColumnDefinitions>
<Grid Grid.Column="0">
<RadioButton Content="{Binding SlotButtons}" Name="SLotButtons" />
</Grid>
</Grid>
</GroupBox>
</Grid>
在Grid.Column="0" 中,我想生成 24 个单选按钮,如上所述。
视图模型:
// Description of SlotButtons
private string _SlotButtons;
public string SlotButtons
{
get
{
return _SlotButtons;
}
set
{
_SlotButtons = value;
OnPropertyChanged("SlotButtons");
}
}
//For RadioButton Click
private ICommand mSlotCommand;
public ICommand SlotCommand
{
get
{
if (mSlotCommand == null)
mSlotCommand = new DelegateCommand(new Action(mSlotCommandExecuted), new Func<bool>(mSlotCommandCanExecute));
return mSlotCommand;
}
set
{
mSlotCommand = value;
}
}
public bool mSlotCommandCanExecute()
{
return true;
}
public void mSlotCommandExecuted()
{
// Logic to implement on a specific radiobutton click using Index
}
我在我的 C++ 应用程序中按如下方式完成了此操作:
for(slot = 0; slot < 24; slot++)
{
m_slotButton[slot] = new ToggleButton(String(int(slot)) + String(": None"));
m_slotButton[slot]->addButtonListener(this); // make this panel grab the button press
addAndMakeVisible(m_slotButton[slot]);
}
现在这就是我想要实现的目标:
- 生成 24 个 RadioButtons,内容从
Content = 0: None到23: None。 - 单选按钮的生成方式应为,我们将行分成 3 列,并在每列垂直添加 8 个单选按钮。
- 在任何时候,都必须选中一个单选按钮,不得选中其他单选按钮。在各个索引的帮助下,必须只有一个单击命令来处理所有按钮。
请帮忙:)
【问题讨论】:
-
如果你想使用 MVVM,你不需要手动创建 RadioButtons。您将 ItemsControl 与包含 RadioButton 的 ItemTemplate 一起使用,并将 24 个项目的列表绑定到 ItemsSource 属性
-
要获得 8*3 的网格布局,您可以在 ItemControl 的 ItemsPanel 模板中使用 UniformGrid
-
@nikie:是的,我已经实现过一次。但是我在那里发现了一个问题:当我单击它们时,所有单选按钮都会被检查,即一次必须检查一个:)
-
@StonedJesus:那么你的实现有问题。要么您没有创建 24 个不同的来源,要么您没有正确绑定到正确的来源。 nikie 的解决方案是 MVVM 的正确解决方案。
-
@GazTheDestroyer:等一下用 Nikie 的实现来更新问题 :)
标签: c# .net wpf mvvm radio-button