繁体   English   中英

获取组中的选定单选按钮(WPF)

[英]Get Selected Radio Button in a Group (WPF)

我的程序中有一个ItemsControl ,其中包含一个单选按钮列表。

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

如何以MVVM方式在“ Insertions组中找到所选单选按钮?

我在互联网上找到的大多数例子都涉及在转换器的帮助下设置绑定IsChecked属性的各个布尔属性。

是否有我可以绑定的ListBox SelectedItem的等价物?

想到的一个解决方案是向Insertion实体添加一个IsChecked布尔属性,并将其绑定到Radio按钮的`IsChecked'属性。 这样,您可以在View Model中查看“Checked”单选按钮。

这是一个快速而肮脏的例子。

注意:我忽略了IsChecked也可以为null的事实,你可以使用bool?处理它bool? 如果需要。

简单的ViewModel

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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM