数据绑定 - 单选按钮数据绑定在 wpf 中不起作用



我有这样的"VM"和"模型"代码,它代表具有INotifyPropertyChanged实现的产品类:

型:

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));
    }
}

视图模型:

    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),
        };

并使用列表框查看,其中每个项目都是单选按钮:

<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>

但是每次我单击单选按钮时都没有发生任何事情。在调试模式下,我无法到达setter方法中的断点。

您应该将 IsEnable 绑定直接引用到绑定对象(产品),而不是模板化父级;

<RadioButton GroupName="Gr1" IsChecked="{Binding Path=IsEnable}, UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}">

最新更新