How can I bind a RadioButton in a ControlTemplate
I am using a ListBox with controlTemplate to show a RadioButton with the ListBoxItem. Here i want to set the IsChecked Property of RadioButton to true and does the necessary wpf Binding for this. below is the xaml
<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 behind class for this is
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new ListStylesViewModel();
}
}
ListStyleViewModel class is
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
please advise what i am doing wrong here?
The binding expression
IsChecked="{Binding IsRadioButtonChecked,
RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}"
in the ControlTemplate uses the ListBoxItem as source object. However, ListBoxItem does not have a IsRadioButtonChecked
property.
Since the binding source property is in the ListStylesViewModel instance in the DataContext
of the ListBox, your binding expression should look like this:
IsChecked="{Binding DataContext.IsRadioButtonChecked,
RelativeSource={RelativeSource AncestorType=ListBox}}"
链接地址: http://www.djcxy.com/p/44672.html