获取选定的单选按钮组(WPF) [英] Get Selected Radio Button in a Group (WPF)
问题描述
我有一个的ItemsControl
在我的计划,包含单选按钮的列表。
I have a ItemsControl
in my program that contains a list of radio buttons.
<ItemsControl ItemsSource="{Binding Insertions}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<RadioButton GroupName="Insertions"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
我要如何找到一个MVVM方式在组 的插入
在选定的单选按钮?
How do I find the selected radio button in the group Insertions
in a MVVM manner?
大多数我已经在互联网上找到的例子包括设置你的器isChecked
属性绑定到一个转换器的帮助下单独布尔属性。
Most of the examples I have found on the internet involve setting individual boolean properties that you bind the IsChecked
property to with the help of a converter.
有没有在列表框的等效
的SelectedItem
我可以绑定到?
Is there an equivalent of the ListBox
SelectedItem
that I can bind to?
推荐答案
这所想到的一个解决方案是一个器isChecked
布尔属性添加到您插入的实体和绑定的在单选按钮的`器isChecked的财产。这样你就可以在视图模型检查经过单选按钮。
One solution that comes to mind is to add an IsChecked
boolean property to your Insertion entities and bind that to the `IsChecked' property of the Radio button. This way you can check the 'Checked' radio button in View Model.
下面是一个快速和肮脏的例子。
Here is a quick and dirty example.
注:我忽略了一个事实,即器isChecked也可以是空
,你可以处理,使用布尔?
如果需要的话。
NB: I ignored the fact that the IsChecked can also be null
, you could handle that using bool?
if required.
简单视图模型
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 - 在code后面不显示,因为它具有比大于产生code等没有code
The XAML - The code behind is not shown since it has no code other than than the generated code.
<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>
这篇关于获取选定的单选按钮组(WPF)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!