2014-10-31 94 views
1

有一个。我如何设置所有单选器isChecked属性设置为false

最初他们都设置为false

但是,一旦我点击其中的一个,一个停留在任何时候都如此。

我们的要求是,它们都可以被设置为false。

我试过的东西

<MultiDataTrigger> 
    <MultiDataTrigger.Conditions> 
     <Condition Binding="{Binding IsChecked, 
        RelativeSource={RelativeSource Self}}" Value="True"/> 
     <Condition Binding="{Binding IsPressed, 
        RelativeSource={RelativeSource Self}}" Value="True"/> 
    </MultiDataTrigger.Conditions> 
    <Setter Property="IsChecked" Value="False"/> 
</MultiDataTrigger> 

但它不工作。我知道我可以使用ToggleButton,但我的RadioButtons一次只能检查一个。

这甚至可能吗?

回答

0

你的解决方案仅当鼠标按钮被按下实际(抱着尝试它,你会看到)。 想到的最简单的方法是改变RadioButton有点满足我们的需要:如果再次点击

public class UncheckableRadioButton : RadioButton 
{ 
    protected override void OnToggle() 
    { 
     if (IsChecked == true) 
     IsChecked = false; 
     else base.OnToggle(); 
    } 
} 

Theese定制无线电将取消。

+0

不是我解决我的问题的方式,但对于未来的读者看。 – DeMama 2014-10-31 12:38:52

+0

@DeMama,你是否介意分享你的解决方案(通过编辑或单独的答案)?这可能对其他人非常有用,对我们来说相当有趣,谁回答了这个问题=) – icebat 2014-10-31 12:48:30

+0

在这里,你走了。不过请注意,这个解决方案对于我所需要的非常具体。 – DeMama 2014-10-31 13:10:54

0

我可以马上告诉你,风格不会解决你的问题,因为一旦用户设置了DependencyProperty的值,它将忽略风格设置器,你应该阅读Dependency Property Value Precedence

在另一方面,你可以尝试处理你自己的鼠标点击,当一个单选按钮器isChecked =真,就像这样:

 <RadioButton GroupName="AAA" PreviewMouseLeftButtonDown="RadioButton_PreviewMouseLeftButtonDown"/> 

和:

private void RadioButton_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) 
    { 
     RadioButton radioButton = sender as RadioButton; 

     if (radioButton != null && radioButton.IsChecked.GetValueOrDefault()) 
     { 
      radioButton.IsChecked = false; 
      e.Handled = true; 
     } 
    } 

我觉得这样做诀窍。

+0

如果使用键盘切换收音机会怎么样? =) – icebat 2014-10-31 12:34:33

+0

我想需要你的用户PreviewKeyDown为好,用相同的代码,同时检查如果按下的键是空格键... – Yoav 2014-10-31 12:41:23

0

由于icebat要求,我会后我的解决方案:

我只是创造了一个事件处理程序,我RadioButtons,我比较我的类中定义的某些值:

private int PopupID; 
private bool IsPopupActive; 
private void RadioButton_Click(object sender, RoutedEventArgs e) 
{ 
    RadioButton rb = (RadioButton)sender; 
    string s = (string)rb.Content; 
    int id = int.Parse(s); 

    if (PopupID == id && IsPopupActive == true) 
    { 
     foreach (RadioButton rbb in PopupGrid.Children.OfType<RadioButton>()) 
      rbb.SetValue(RadioButton.IsCheckedProperty, false); 

     IsPopupActive = false; 
    } 
    else if (PopupID != id || IsPopupActive == false) 
    { 
     foreach (RadioButton rbb in PopupGrid.Children.OfType<RadioButton>() 
       .Where(x => x != rb)) 
      rbb.SetValue(RadioButton.IsCheckedProperty, false); 

     IsPopupActive = true; 
     PopupID = id; 
    } 
} 

不是一个大风扇这样的代码隐藏解决方案,但它的工作原理。