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

查看:27
本文介绍了如何为 ListView 控件中的第一个 WPF RadioButton 设置 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 RadioButton 设置 XAML,以便默认检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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