c# - 如何在WPF中基于索引动态生成Togglebutton并对其执行操作

标签 c# .net wpf mvvm checkbox

我正在开发一个 WPF,我需要在其中动态生成 16 次 Togglebutton。如果我写下这个切换按钮 16 次并为它们设置单独的按钮单击命令,那将是低效的。

XAML:

<Togglebutton Height="14" Command="{Binding TogglebuttonGen}" Margin="0" Name="checkBox1" Grid.Column="0" VerticalAlignment="Center" HorizontalAlignment="Center" />

理想情况下,我希望生成它们 16 次,并在我的 viewmodel 类中使用一种通用方法,如下所示:
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
    }

我在我的 C++ 应用程序中完成了如下操作:
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;
}

因此,它生成了 16 次,并且有一种方法基于 index i 执行操作.

如何在我的 wpf 应用程序中实现它? :)

最佳答案

在您的 View 模型中,创建一个包含 16 个 ToggleAction 类实例的集合。

public ObservableCollection<MyToggleActionClass> MyItems {get;set;}


public class MyToggleActionClass
{
   public string DisplayName {get;set;}
   public int Index {get;set;}
}

将此集合绑定(bind)到 ItemsControl 的 ItemsSource,就是这样。
<ItemsControl ItemsSource="{Binding MyItems}">
 <ItemsControl.ItemTemplate>
  <DataTemplate>
    <ToggleButton Content="{Binding Displayname}"
                  Command="{Binding DataContext.TogglebuttonGen, RelativSource={RelativSource AncestorType=ItemsControl}}"
                  CommandParameter="{Binding Index}"/>
  </DataTemplate>
 </ItemsControl.ItemTemplate>
</ItemsControl>

这都是手写的,所以请检查是否有错误。最重要的是命令绑定(bind)。如果要从 ViewModel 调用命令,则必须使用 RelativeSource 走到 ViewModel DataContext。

我还将在 MyToggleActionClass 中处理/绑定(bind)切换状态。

关于c# - 如何在WPF中基于索引动态生成Togglebutton并对其执行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13048058/

相关文章:

c# - 自定义引用循环处理

WPF 动画 StrokeDashArray

wpf - 当用户在菜单外单击时,如何使WPF上下文菜单消失?

c# - C# 中的错误代码通过 CLR 书

c# - 在 C 中查找事件用户目录的路径

c# - Android 单声道 : Splash screen tutorial c#

c# - Unity中的随机数组

.net - Visual Studio 2010 中 xsd.exe 的替代品

c# - NEST 2.0和ElasticSearch 2中的重大更改

wpf - 如何强制关闭 ContextMenu(WPF 项目)?