How can I set the XAML for the first WPF RadioButton in a ListView control to be checked by default?

大憨熊 提交于 2019-12-22 05:58:25

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/3247801/how-can-i-set-the-xaml-for-the-first-wpf-radiobutton-in-a-listview-control-to-be

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!