WPF ListView与RadioButtons组并选择默认值

时间:2014-06-12 07:36:29

标签: c# wpf xaml wpf-controls

今天我选择默认CheckBox时出现问题。但首先我展示我的代码:

<ScrollViewer>
    <ListView ItemsSource="{Binding itemsSource, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <Expander IsExpanded="True">
                    <Expander.Header>
                        <Label Content="{Binding AttrName, Mode=OneWay}" />
                    </Expander.Header>

                    <ListView Margin="20, 0, 0, 0" ItemsSource="{Binding subItemSource}" BorderBrush="Transparent" >
                        <ListView.ItemTemplate>
                            <DataTemplate>
                                <RadioButton GroupName="{Binding DataContext.AttrName, RelativeSource={RelativeSource AncestorType=ItemsControl}}"
                                                    Content="{Binding}"
                                                    <!-- What should I bind to to get item checked? -->
                                                    IsChecked={}/>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>

                </Expander>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ScrollViewer>

所以我有一个嵌套绑定,在CheckBoxes中我将GroupName绑定到父数据上下文。我的itemsSource包含以下属性:

int DefaultValue { get; set; }
List<int> subItemSource { get; set; }

现在我想要的是在实际绑定值等于RadioButton时标记DefaultValue。我该怎么做?我应该写验证器吗?

1 个答案:

答案 0 :(得分:3)

我将首先编写转换器类

class ElementComparer : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return values[0] == values[1];
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

然后将转换器声明为资源,其中l:是转换器的命名空间

<l:ElementComparer x:Key="ElementComparer"/>

然后在您的数据模板中

<DataTemplate>
    <RadioButton GroupName="{Binding DataContext.AttrName, RelativeSource={RelativeSource AncestorType=ItemsControl}}"
                 Content="{Binding}"
        <RadioButton.IsChecked>
            <MultiBinding Converter="{StaticResource ElementComparer}" Mode="OneWay">
                <Binding Path="DataContext.DefaultValue" RelativeSource="{RelativeSource AncestorType=ItemsControl}"/>
                <Binding />
            </MultiBinding>
        </RadioButton.IsChecked>

如果ItemsControl的datacontext包含要与之比较的默认值的属性,则诀窍是将列表的选定项目与当前项目进行比较以检测它是否为默认项目,并将从转换器返回true并且因此将检查无线电