[英]Radiobutton databinding don't work in wpf
I have such "VM" and "Model" code, thats represent Product class with implementation of INotifyPropertyChanged: 我有这样的“ VM”和“ Model”代码,它们代表具有INotifyPropertyChanged实现的Product类:
Model: 模型:
public class Product : INotifyPropertyChanged
{
public Product(string name, bool isEnable)
{
Name = name;
IsEnable = isEnable;
}
public string Name { get; set; }
private bool _isEnable;
public bool IsEnable
{
get { return _isEnable; }
set
{
if (value != _isEnable)
{
_isEnable = value;
OnPropertyChanged("IsEnable");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
ViewModel: ViewModel:
public ObservableCollection<Product> Products
{
get { return _products; }
set { _products = value;}
}
private ObservableCollection<Product> _products = new ObservableCollection<Product>()
{
new Product("a", false),
new Product("b", false),
new Product("c", false),
};
And View with ListBox where each Item is RadioButton: 然后使用ListBox进行查看,其中每个项目都是RadioButton:
<Window.Resources>
<Style x:Key="RadioButtonListStyle" TargetType="{x:Type ListBox}">
<Setter Property="SelectionMode" Value="Single"></Setter>
<Setter Property="ItemContainerStyle">
<Setter.Value>
<Style TargetType="{x:Type ListBoxItem}" >
<Setter Property="Margin" Value="2" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<RadioButton GroupName="Gr1"
IsChecked="{Binding Path=IsEnable,RelativeSource={RelativeSource TemplatedParent},
UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}">
<ContentPresenter></ContentPresenter>
</RadioButton>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid Margin="5">
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<ListBox x:Name="UserList" Style="{StaticResource RadioButtonListStyle}" ItemsSource="{Binding Products}">
</ListBox>
</Grid>
But nothing happened every time when I click to the radiobutton. 但是,每当我单击单选按钮时,什么都没有发生。 I could not reach to a breakpoint in the setter method on debug mode. 在调试模式下,我无法在setter方法中达到断点。
您应该将IsEnable绑定直接引用到绑定的对象(产品),而不是模板父。
<RadioButton GroupName="Gr1" IsChecked="{Binding Path=IsEnable}, UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.