【问题标题】:Get Selected Radio Button in a Group (WPF)获取组中选定的单选按钮 (WPF)
【发布时间】:2011-05-24 04:24:14
【问题描述】:

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

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

如何以 MVVM 的方式在 group Insertions 中找到选中的单选按钮?

我在 Internet 上找到的大多数示例都涉及在转换器的帮助下设置您将 IsChecked 属性绑定到的各个布尔属性。

我可以绑定到 ListBox SelectedItem 的等效项吗?

【问题讨论】:

    标签: c# wpf mvvm binding radio-button


    【解决方案1】:

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

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

    注意:我忽略了 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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-10
      • 1970-01-01
      • 2021-12-29
      • 2011-07-28
      • 1970-01-01
      • 2016-08-30
      相关资源
      最近更新 更多