在代码或样式/模板中绑定自定义附加属性

时间:2013-06-12 18:42:26

标签: c# wpf

我有这个WPF,通过以下形式重复:

<WrapPanel local:RadioChecker.IsChecked="False">
    <RadioButton Content="Yes" Height="16" GroupName = "rbgSeizure" Name="rbSeizureYes" 
                    local:RadioChecker.IsChecked="{Binding RelativeSource={RelativeSource Self}, Path=IsChecked}" />
    <RadioButton Content="No"  Height="16" GroupName = "rbgSeizure" Name="rbSeizureNo" 
                    local:RadioChecker.IsChecked="{Binding RelativeSource={RelativeSource Self}, Path=IsChecked}" />
</WrapPanel>

如何以相同的方式设置每个WrapPanel以及每个RadioButton,而无需将上述local:...复制并粘贴到每个控件上

我可以在后面的代码中获得每个类型控件,如:

GetLogicalChildCollection<RadioButton>(mainPanel)
    .ForEach(rb =>
    {
        Binding binding = new Binding();
        //binding.Source
    });

但我不确定如何设置绑定的/将自定义附加属性附加到控件。

1 个答案:

答案 0 :(得分:1)

应该是这样的:

GetLogicalChildCollection<RadioButton>(mainPanel).ForEach(
    rb =>
    {
        var binding = new Binding
        {
            Path = new PropertyPath(RadioButton.IsCheckedProperty),
            Source = rb
        };               
        rb.SetBinding(RadioChecker.IsCheckedProperty, binding);
    });

或者这个:

GetLogicalChildCollection<RadioButton>(mainPanel).ForEach(
    rb => rb.SetBinding(RadioChecker.IsCheckedProperty,
                        new Binding("IsChecked") { Source = rb }));