2010-11-21 152 views
6

我试图绑定到RadioButton.IsChecked属性,它只能工作一次。在那之后,绑定无法正常工作,我不知道为什么会发生这种情况。任何人都可以帮忙吗?谢谢!RadioButton IsChecked失去约束力

这是我的代码。

C#

public partial class Window1 : Window 
{ 
    public Window1() 
    { 
     InitializeComponent(); 

     this.DataContext = new ViewModel(); 
    } 
} 

public class ViewModel 
{ 
    private bool _isChecked1 = true; 
    public bool IsChecked1 
    { 
     get { return _isChecked1; } 
     set 
     { 
      if (_isChecked1 != value) 
      { 
       _isChecked1 = value; 
      } 
     } 
    } 

    private bool _isChecked2; 
    public bool IsChecked2 
    { 
     get { return _isChecked2; } 
     set 
     { 
      if (_isChecked2 != value) 
      { 
       _isChecked2 = value; 
      } 
     } 
    } 
} 

XAML:

<Grid> 
    <StackPanel> 
     <RadioButton Content="RadioButton1" IsChecked="{Binding IsChecked1}" /> 
     <RadioButton Content="RadioButton2" IsChecked="{Binding IsChecked2}" /> 
    </StackPanel> 
</Grid> 

回答

5

这是一个不幸的known bug。我假设在WPF 4.0中已经修复了这个问题,因为新的DependencyObject.SetCurrentValue API尚未验证。

+1

啊,这太可怕了。我想我必须回到事件处理程序......除此之外,您还知道任何解决方法吗? – Carlo 2010-11-21 00:38:34

+0

使用'ListBox'并将每个'ListBoxItem'设置为'RadioButton'。 http://code.msdn.microsoft.com/wpfradiobuttonlist – 2010-11-21 00:43:15

0

我猜你需要实现INotifyPropertyChanged接口

public event PropertyChangedEventHandler PropertyChanged; 

private void NotifyPropertyChanged(String info) 
{ 
    if (PropertyChanged != null) 
    { 
     PropertyChanged(this, new PropertyChangedEventArgs(info)); 
    } 
} 


private bool _isChecked1 = true; 
public bool IsChecked1 
{ 
    get { return _isChecked1; } 
    set 
    { 
     if (_isChecked1 != value) 
     { 
      _isChecked1 = value; 
      NotifyPropertyChanged("IsChecked1"); 
     } 
    } 
} // and the other property... 

:)

+0

试过了,它不起作用。感谢您的建议。 – Carlo 2010-11-29 19:18:38

1

只是在这里肯特的答案的后续......这实际上已在WPF 4.0中修复,我在我当前的项目中利用了这种行为。取消激活的单选按钮现在将其绑定值设置为false,而不是中断绑定。