WPF:以编程方式创建CheckBox

时间:2013-09-05 08:44:20

标签: c# wpf

如何从代码创建此代码?

<CheckBox Command="{Binding Source={StaticResource VMLocator}, Path=TimeTableInformationViewModel.MyCommand }"
                  CommandParameter="{Binding valueFromInput}" />

我不确定如何从代码后面设置Command属性:

    public static DataTemplate CreateDataTemplate()
    {
        var block = new FrameworkElementFactory(typeof(CheckBox));
        block.SetBinding(CheckBox.CommandProperty, new Binding(""));
        DataTemplate newDataTemplate = new DataTemplate() { VisualTree = block };

    }

1 个答案:

答案 0 :(得分:2)

试试这个:

TypeOfYourObject vmLocator = (TypeOfYourObject)Resources["VMLocator"];
CheckBox checkBox = new CheckBox();
checkBox.Command = vmLocator.TimeTableInformationViewModel.MyCommand;
checkBox.CommandParameter = vmLocator.valueFromInput;

更新&gt;&gt;&gt;

有很多方法可以做到这一点,但我添加了一个简单的示例,其中包括设置Binding ...以获取更多信息,请参阅How do I build a DataTemplate in c# code?帖子查找如何在代码中创建更大的DataTemplate

FrameworkElementFactory checkbox = new FrameworkElementFactory(typeof(CheckBox));
checkBox.Name = "aCheckBox";
checkBox.SetBinding(TextBlock.IsCheckedProperty, new Binding("YourBoolProperty"));
DataTemplate dataTemplate = new DataTemplate() { VisualTree = checkbox };