在一个组中获取选中的单选按钮(WPF)

9

我在程序中有一个包含一组单选按钮的ItemsControl

<ItemsControl ItemsSource="{Binding Insertions}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <RadioButton GroupName="Insertions"/>
                </Grid>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

如何以MVVM方式找到选定的单选按钮在 插入 中?

我在互联网上找到的大多数示例都涉及设置单个布尔属性,您可以使用转换器将其绑定到 IsChecked 属性。

是否有一个类似于 ListBoxSelectedItem 可以绑定的东西?

1个回答

11

我想到的一个解决方案是在插入实体中添加一个IsChecked布尔属性并将其绑定到单选按钮的`IsChecked'属性。这样,您就可以在视图模型中检查“已选中”的单选按钮。

以下是一个简单而粗略的示例。

NB:我忽略了IsChecked也可以是null的事实,如果需要,您可以使用bool?来处理它。

这是一个简单的视图模型。

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace WpfRadioButtonListControlTest
{
  class MainViewModel
  {
    public ObservableCollection<Insertion> Insertions { get; set; }

    public MainViewModel()
    {
      Insertions = new ObservableCollection<Insertion>();
      Insertions.Add(new Insertion() { Text = "Item 1" });
      Insertions.Add(new Insertion() { Text = "Item 2", IsChecked=true });
      Insertions.Add(new Insertion() { Text = "Item 3" });
      Insertions.Add(new Insertion() { Text = "Item 4" });
    }
  }

  class Insertion
  {
    public string Text { get; set; }
    public bool IsChecked { get; set; }
  }
}

XAML代码的后台逻辑没有显示,因为除了生成的代码之外,它没有其他的代码。

<Window x:Class="WpfRadioButtonListControlTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfRadioButtonListControlTest"
        Title="MainWindow" Height="350" Width="525">
  <Window.Resources>
    <local:MainViewModel x:Key="ViewModel" />
  </Window.Resources>
  <Grid DataContext="{StaticResource ViewModel}">
    <ItemsControl ItemsSource="{Binding Insertions}">
      <ItemsControl.ItemTemplate>
        <DataTemplate>
          <Grid>
            <RadioButton GroupName="Insertions" 
                         Content="{Binding Text}" 
                         IsChecked="{Binding IsChecked, Mode=TwoWay}"/>
          </Grid>
        </DataTemplate>
      </ItemsControl.ItemTemplate>
    </ItemsControl>
  </Grid>
</Window>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接