如何在ListView控件中为默认情况下检查的第一个WPF RadioButton设置XAML?

Val*_*l M 5 wpf binding listview wpf-controls radio-button

我有一个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>
Run Code Online (Sandbox Code Playgroud)

OptionsSortedByKey属性是SortedList.

我通过在Loaded事件中设置RadioButton控件的IsChecked属性来做到这一点:

        var button = sender as RadioButton;

        if (button != null)
        {
            if (button.Content.ToString().ToUpperInvariant() == "ALL")
            {
                button.IsChecked = true;
            }
        }
Run Code Online (Sandbox Code Playgroud)

我更喜欢通过XAML中的数据绑定来做到这一点.有一个简单的方法吗?

Ken*_*art 7

你可以:

<RadioButton IsChecked="{Binding RelativeSource={PreviousData}, Converter={StaticResource NullAsTrueConverter}}"/>
Run Code Online (Sandbox Code Playgroud)

true如果值为,转换器返回的位置null.

也就是说,基于MVVM的方法会使这一点变得轻而易举.你只是:

<RadioButton IsChecked="{Binding IsChecked}"/>
Run Code Online (Sandbox Code Playgroud)

然后,你的主视图模式将设置IsCheckedtrue集合中的第一个子视图模型.