首页 > 解决方案 > WPF单选按钮组如何在选择任何项目时启用文本框?

问题描述

通过简单地绑定控件的 IsEnabled 属性,我可以毫无问题地让此功能与文本框和组合框一起使用,我希望保持隐藏状态,直到为 .Text 属性选择某些内容,如下所示:

<Label Content="Please Select the status for this client:" Margin="0,0,65,0" IsEnabled="{Binding CBCustomer.Text}" />

所以基本上这个项目不会显示,直到有人在 ComboBox 中选择了一些东西。

如何使用一组单选按钮获得相同的功能?基本上我有一个堆栈面板,我希望 IsEnabled 属性(显示为 XXXXXX)绑定到是否选择了任何按钮的布尔值。

  <StackPanel Orientation="Horizontal" Canvas.Left="54"  Canvas.Top="40" Margin="0,0,0,50">
            <Label Content="Please Select the RAG Status for this client:" Margin="0,0,65,0" IsEnabled="{Binding CBCustomer.Text}" />
            <RadioButton GroupName="RAGGroup" Margin="0,8,0,0" Background="Red" Foreground="Red" IsEnabled="{Binding CBCustomer.Text}">Red</RadioButton>
            <RadioButton GroupName="RAGGroup" Margin="10,8,0,0" Background="DarkGoldenrod" Foreground="DarkGoldenrod" IsEnabled="{Binding CBCustomer.Text}">Amber</RadioButton>
            <RadioButton GroupName="RAGGroup" Margin="10,8,0,0" Background="Green" Foreground="Green" IsEnabled="{Binding CBCustomer.Text}">Green</RadioButton>
        </StackPanel>

  <StackPanel Margin="55,80,0,0" IsEnabled="{Binding XXXXXXX}">

使用多重绑定?我看到了一些示例,这些示例显示了如何从选定的按钮中取回值,但我并不关心,我只需要查看是否选择了该值。

标签: c#wpfdata-bindingradio-group

解决方案


如果要绑定到其他元素,可以使用DataTriggers

<RadioButton x:Name="RB1"/>
<RadioButton x:Name="RB2"/>
<RadioButton x:Name="RB3"/>
<StackPanel>
    <StackPanel.Style>
        <Style TargetType="StackPanel">
            <Setter Property="IsEnabled" Value="False"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=RB1, Path=IsChecked}" Value="True">
                    <Setter Property="IsEnabled" Value="True"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding ElementName=RB2, Path=IsChecked}" Value="True">
                    <Setter Property="IsEnabled" Value="True"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding ElementName=RB3, Path=IsChecked}" Value="True">
                    <Setter Property="IsEnabled" Value="True"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </StackPanel.Style>
</StackPanel>

但我几乎总是绑定到数据层,比如:

<RadioButton IsChecked="{Binding RAG, Converter=...}"/>
<RadioButton IsChecked="{Binding RAG, Converter=...}"/>
<RadioButton IsChecked="{Binding RAG, Converter=...}"/>
<StackPanel>
    <StackPanel.Style>
        <Style TargetType="StackPanel">
            <Setter Property="IsEnabled" Value="True"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding RAG}" Value="{x:Null}">
                    <Setter Property="IsEnabled" Value="False"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </StackPanel.Style>
</StackPanel>

推荐阅读