0

我有这样的“VM”和“模型”代码,它代表具有 INotifyPropertyChanged 实现的 Product 类:

模型:

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

并使用 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>

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

4

1 回答 1

1

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

<RadioButton GroupName="Gr1" IsChecked="{Binding Path=IsEnable}, UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}">
于 2013-01-26T23:19:59.290 回答