如何设置 ListView 控件中第一个 WPF RadioButton 的 XAML 默认选中?

发布于 2024-09-09 06:43:04 字数 962 浏览 1 评论 0原文

我有一个 WPF ListView 控件,其中包含许多使用数据绑定的 RadioButton 控件。我希望默认情况下检查组中的第一个 RadioButton,最好在 XAML 中设置而不是以编程方式设置,但尚未成功实现此目的。

我的控件 XAML 是:

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

OptionsSortedByKey 属性是一个 SortedList。

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

        var button = sender as RadioButton;

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

我更喜欢通过 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.

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>

The OptionsSortedByKey property is a SortedList.

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;
            }
        }

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无语# 2024-09-16 06:43:04

您可以:

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

如果值为 null,转换器将返回 true

也就是说,基于 MVVM 的方法将使这一切变得轻而易举。您只需:

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

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

You could:

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

Where the converter returns true if the value is null.

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

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文