我有一个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中的数据绑定来实现。有一个简单的方法吗?
答案 0 :(得分:7)
你可以:
<RadioButton IsChecked="{Binding RelativeSource={PreviousData}, Converter={StaticResource NullAsTrueConverter}}"/>
如果值为true
,则转换器返回null
。
也就是说,基于MVVM的方法会使这一点变得轻而易举。你只是:
<RadioButton IsChecked="{Binding IsChecked}"/>
然后,您的主视图模型会为集合中的第一个子视图模型设置IsChecked
到true
。