Jednym z rozwiązań, które przychodzi na myśl, jest dodanie wartości boolean o wartości IsChecked
do elementów wstawiania i powiązanie jej z właściwością `IsChecked 'przycisku Radio. W ten sposób możesz zaznaczyć przycisk "Sprawdzone" w widoku modelu.
Oto szybki i brudny przykład.
UWAGA: I zignorował fakt, że może być również IsChecked null
, można obsługiwać za pomocą bool?
że w razie potrzeby.
Prosta 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 - Kod tyłu nie jest pokazany, ponieważ nie ma żadnego kodu innego niż niż wygenerowanego kodu.
<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>