2010-11-21 101 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,而不是中斷綁定。