如何为要默认检查的ListView控件中的第一个WPF单选按钮设置XAML? [英] How can I set the XAML for the first WPF RadioButton in a ListView control to be checked by default?

查看:127
本文介绍了如何为要默认检查的ListView控件中的第一个WPF单选按钮设置XAML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个WPF ListView控件,其中包含许多使用数据绑定的RadioButton控件.我希望默认情况下检查组中的第一个RadioButton,最好在XAML中进行设置,而不是通过编程方式进行设置,但是并没有设法实现这一点.

I have a WPF ListView control containing a number of RadioButton controls using data binding. I'd like the first RadioButton in the group to be checked by default, preferably set in the XAML rather than programmatically, but haven't managed to achieve this.

我用于控件的XAML是:

My XAML for the control is:

        <ListView ItemsSource="{Binding OptionsSortedByKey}" >
            <ListView.ItemTemplate>
                <DataTemplate DataType="{x:Type Logging:FilterOptionsRadioListViewModel}">
                    <RadioButton Content="{Binding Value}" />
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

OptionsSortedByKey属性是一个SortedList.

The OptionsSortedByKey property is a SortedList.

我笨拙地通过在Loaded事件中设置RadioButton控件的IsChecked属性来完成此操作:

I have done this clumsily by setting the IsChecked property of the RadioButton control in the Loaded event:

        var button = sender as RadioButton;

        if (button != null)
        {
            if (button.Content.ToString().ToUpperInvariant() == "ALL")
            {
                button.IsChecked = true;
            }
        }

我更愿意通过XAML中的数据绑定来做到这一点.有没有简单的方法?

I'd far prefer to do it via data binding in the XAML. Is there a simple way?

推荐答案

您可以:

<RadioButton IsChecked="{Binding RelativeSource={PreviousData}, Converter={StaticResource NullAsTrueConverter}}"/>

如果值是null,转换器将在其中返回true.

Where the converter returns true if the value is null.

也就是说,基于MVVM的方法将使其变得轻而易举.您只需:

That said, an MVVM-based approach would make this a snap. You'd just:

<RadioButton IsChecked="{Binding IsChecked}"/>

然后您的主视图模型会将集合中的第一个子视图模型的IsChecked设置为true.

And then your primary view model would set IsChecked to true for the first child view model in the collection.

这篇关于如何为要默认检查的ListView控件中的第一个WPF单选按钮设置XAML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆