views:

161

answers:

1

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?

A: 

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.

HTH,
Kent

Kent Boogaart
Kent, that looks great. I'd been avoiding creating a child view model by using a SortedList as my collection. A better approach would be to create a child view model class with just the DictionaryEntry fields and the IsChecked property, would it? Easy enough to do, I was just trying to minimise work by using the collection class that seemed to meet all my needs.
Val M
@Val: yes, I tend to create VMs that wrap the data items - even if they're very simple. Whenever I put it off and attempted to get away with just using the data item, I always ended up regretting it...
Kent Boogaart
Kent, that is exactly what I have done now and have since found other properties that the child VM needs anyway so it's been great having the child VM already in place. I won't try and take short cuts again. Thanks for the help.
Val M