WPF radiobuttons IsHitTestVisible不工作

时间:2016-10-21 08:12:14

标签: c# .net wpf xaml

我在列表框中使用单选按钮并且无法禁用它们。 搜索后,我找到了有关IsEnabled和IsHitTestVisible的链接。当我将IsEnabled设置为false时,按钮和文本变为灰色,但它仍然可以点击。设置IsHitTestVisible不会改变这一点。我的XAMLcode看起来像这样:

<ListBox ItemsSource="{Binding Source}" BorderThickness="0" VerticalAlignment="Stretch" Background="Transparent" SelectedItem="{Binding SelectedSource, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" >
    <ListBox.ItemTemplate>
        <DataTemplate>
            <RadioButton IsHitTestVisible="{Binding IsEnabled}"  IsEnabled="{Binding IsEnabled}" Margin="0 2 0 0" FontSize="12" FontFamily="Segoe UI Regular" Content="{Binding name}" GroupName="GroupList"  >
                <RadioButton.Style>
                    <Style TargetType="{x:Type RadioButton}">
                        <Setter Property="IsChecked" Value="{Binding Path=IsSelected, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}}" />
                    </Style>
                </RadioButton.Style>
            </RadioButton>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox> 

计算并返回bool的c#中的属性。

public bool IsEnabled
{     
    get
    {
        IsEnabledCalculate();
        return isEnabled;
    }
}

有关如何禁用选择的任何想法?

1 个答案:

答案 0 :(得分:1)

IsHitTestVisible的{​​{1}}上使用RadioButton是个不错的开始。这样,当您点击ListBox时,活动就会通过&#34;它由RadioButton处理(项目被选中)。然后,您可以通过绑定ListBoxItem的{​​{1}}属性来操纵IsChecked属性。

然而,这仍然不足以实现你想要的。首先,您将IsSelected属性绑定在错误的级别:ListBoxItem。正如您所注意到的,这仍然允许IsEnabled被选中。因此,您需要将RadioButton属性绑定到ListBoxItem的{​​{1}}属性,而不是:

IsEnabled

这里仍有一个小问题。在代码隐藏中更改IsEnabled属性后,ListBoxItm将被禁用,但仍会检查 <ListBox.ItemContainerStyle> <Style TargetType="{x:Type ListBoxItem}"> <Setter Property="IsEnabled" Value="{Binding Path=IsEnabled}"/> </Style> </ListBox.ItemContainerStyle> 。为了防止这种情况发生,并在项目被禁用时取消选中IsEnabled,您可以使用ListBoxItem

RadioButton