用于更改背景颜色的按钮

时间:2017-11-17 12:51:08

标签: xaml uwp

我正在开发一个UWP应用程序。我希望单击时可以使用单选按钮更改主页和设置页面的背景。下面的单选按钮代码位于Settings.xaml.cs

private void BGRadioButtonGreen_Checked(object sender, RoutedEventArgs e)
    {
        MainPage.Background = Brushes.Red??;
    }

在这个例子中,我试图选择一个单选按钮,让它将设置和主页背景更改为Green.However它似乎不起作用。提前致谢

2 个答案:

答案 0 :(得分:0)

您可以设置根网格的背景颜色。如下面的示例所示,在单选按钮检查后,颜色将变为红色。这应该是你正在寻找的。

<Page
x:Class="Test.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Test"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" Background="Blue">

<Grid x:Name="MainGrid" Background="Green">
    <StackPanel>
        <RadioButton Content="Red" Tag="Green" Checked="RadioButton_Checked"/>
    </StackPanel>
</Grid>

private void RadioButton_Checked(object sender, RoutedEventArgs e)
{
    MainGrid.Background = new SolidColorBrush(Windows.UI.Colors.Red);
}

答案 1 :(得分:0)

要更改背景颜色,如@ColdMorningLight所述,您应该为Background属性设置SolidColorBrush值。

由于您尝试更改MainPage页面中的Settings背景颜色(位于不同页面),您还需要首先获取当前MainPage实例,然后设置页面&# 39; s背景。例如:

MainPage mainPage;
public SettingPage()
{
    this.InitializeComponent();
    mainPage = (Window.Current.Content as Frame).Content as MainPage;
}

private void radchangecolor_Checked(object sender, RoutedEventArgs e)
{
    mainPage.Background = new SolidColorBrush(Windows.UI.Colors.Green);
}

注意我设置页面背景颜色,只有在根面板背景颜色透明时才能看到效果(默认值为Background="{ThemeResource ApplicationPageBackgroundThemeBrush}")。否则,您需要更改根面板背景颜色。例如,如下MainPage将生效:

<Page
   ...
    mc:Ignorable="d"  >
    <StackPanel>
        <Frame x:Name="frame" Height="200" Width="300" Background="Azure"></Frame>
        <Button x:Name="btntest" Click="btntest_Click" Content="test"></Button>
    </StackPanel>
</Page>