根据RadioButton

时间:2016-05-14 15:45:08

标签: wpf c#-4.0 data-binding

我有一个灰色的网格,包含3个radiobutton' Yes / No / Pending'现在,我想根据所选的值更改网格的颜色。

如果值为yes,则网格将变为绿色。

如果valie为No,则网格将变为红色,依此类推。

我希望所有这些都发生在xaml中,只有后面没有代码, 这是我的代码:

<Grid Background="#FFF2F2F2" Height="34" HorizontalAlignment="Left" Name="grid19" VerticalAlignment="Top" Width="151">
                        <RadioButton Content="Yes" Height="16" HorizontalAlignment="Left" Margin="2,12,0,0" Name="radioButton1" VerticalAlignment="Top" />
                        <RadioButton Content="No" Height="16" HorizontalAlignment="Left" Margin="46,12,0,0" Name="radioButton2" VerticalAlignment="Top" />
                        <RadioButton Content="Pending" Height="16" HorizontalAlignment="Left" Margin="86,12,0,0" Name="radioButton3" VerticalAlignment="Top" />
                    </Grid>

非常感谢^^

1 个答案:

答案 0 :(得分:0)

<Grid Height="60" HorizontalAlignment="Left" Name="grid19" VerticalAlignment="Top" Width="151">
        <RadioButton Content="Yes" Height="16" HorizontalAlignment="Left" Margin="2,12,0,0" Name="radioButton1" VerticalAlignment="Top" />
        <RadioButton Content="No" Height="16" HorizontalAlignment="Left" Margin="46,12,0,0" Name="radioButton2" VerticalAlignment="Top" />
        <RadioButton Content="Pending" Height="16" HorizontalAlignment="Left" Margin="86,12,0,0" Name="radioButton3" VerticalAlignment="Top" />
        <Grid.Style>
            <Style TargetType="Grid">
                <Setter Property="Background" Value="#FFF2F2F2" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ElementName=radioButton1, Path=IsChecked}" Value="True">
                        <Setter Property="Background" Value="Red" />
                    </DataTrigger>
                    <DataTrigger Binding="{Binding ElementName=radioButton2, Path=IsChecked}" Value="True">
                        <Setter Property="Background" Value="Blue" />
                    </DataTrigger>
                    <DataTrigger Binding="{Binding ElementName=radioButton3, Path=IsChecked}" Value="True">
                        <Setter Property="Background" Value="Green" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Grid.Style>
    </Grid>

请注意,我已删除默认背景并将其添加为设置器,因为直接添加它将覆盖所有其他背景属性。希望这会对你有所帮助。