[英]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.