Radiobutton数据绑定在wpf中不起作用

时间:2013-01-26 22:45:12

标签: wpf data-binding mvvm radio-button

我有这样的“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方法中达到断点。

1 个答案:

答案 0 :(得分:0)

您应该将IsEnabled Binding直接引用到绑定对象(Product),而不是引用Templatedparent;

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