J'utilise un ListBox avec controlTemplate pour afficher un RadioButton avec le ListBoxItem. Ici, je veux définir la propriété IsChecked de RadioButton à true et fait la liaison wpf nécessaire pour cela. ci-dessous est le XAMLComment puis-je lier un RadioButton dans un ControlTemplate
<ListBox ItemsSource="{Binding Products}" DisplayMemberPath="ProductName" Grid.Column="0" Width="250" HorizontalAlignment="Left" Margin="0,2,0,30" AlternationCount="2">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Margin" Value="2"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<RadioButton IsChecked="{Binding IsRadioButtonChecked, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}">
<ContentPresenter></ContentPresenter>
</RadioButton>
</ControlTemplate>
</Setter.Value>
</Setter>
<!--Alternate Style Indexing-->
<Style.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="LightGray"></Setter>
</Trigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
code derrière pour cette classe est
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new ListStylesViewModel();
}
}
classe ListStyleViewModel est
public class ListStylesViewModel : INotifyPropertyChanged
{
private string prodName;
private List<Products> products;
private bool isChecked = true;
public ListStylesViewModel()
{
ListStyleModel model = new ListStyleModel();
this.Products = model.GetProducts();
}
public string ProductName
{
get
{
return this.prodName;
}
set
{
this.prodName = value;
this.OnPropertyChanged("ProductName");
}
}
public List<Products> Products
{
get
{
return this.products;
}
set
{
this.products = value;
this.OnPropertyChanged("Products");
}
}
public bool IsRadioButtonChecked
{
get
{
return this.isChecked;
}
set
{
this.isChecked = value;
this.OnPropertyChanged("IsChecked");
}
}
#region
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string pptName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(pptName));
}
}
#endregion
s'il vous plaît conseiller ce que je fais mal ici?
Je pense que le principal problème est que votre 'IsRadioButtonChecked' est mis en œuvre à l'intérieur 'ListStylesViewModel' alors qu'il devrait être implémenté dans' Products', donc l'état vérifié est suivi pour chaque élément au lieu d'une seule fois pour toute la liste. – grek40
je veux que le RadioButton soit implémenté dans ListStyleViewModel seulement, a obtenu la réponse maintenant. (Besoin de mettre DataContext sur ce contrôle) – Arvind