如何更改XAML网格背景

时间:2018-10-14 01:34:01

标签: c# xaml uwp background imagebrush

我具有以下XAML代码来创建Windows通用应用程序:

<Page
x:Class="CalculationQuizzer.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:CalculationQuizzer"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Image Source="ms-appx:///Images/kingscross.jpg" Opacity=".3" Stretch="Fill"></Image>
    <StackPanel VerticalAlignment="Center">
        <TextBlock Text="Calculation Quizzer" TextAlignment="Center" Margin="4" FontSize="16"></TextBlock>
        <TextBlock Name="questionTextBlock" Text="" TextAlignment="Center" Margin="4"></TextBlock>
        <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Margin="4">
            <TextBox Name="answerTextBox" Width="100" Margin="4" TextAlignment="Center"></TextBox>
            <Button Content="Check Answer" Name="checkAnswerButton" HorizontalAlignment="Center"  Margin="4" Click="checkAnswerButton_Click" ></Button>
        </StackPanel>
        <Button Content="Next Question" Name="getNextQuestionButton" HorizontalAlignment="Center"  Margin="4" Click="getNextQuestionButton_Click" ></Button>
        <TextBlock Name="resultTextBlock" Text="" TextAlignment="Center" Margin="4"></TextBlock>
    </StackPanel>
    <MediaElement Name="soundMediaElement"></MediaElement>
</Grid>

如您所见,表格的背景使用了名为kingscross.jpg的图像。我试图这样做,以便单击按钮Next Answer会导致网格背景更改为名为SKV_8915_s.jpg的图像。

以下是XAML后面的代码:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Xaml.Media.Imaging;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace CalculationQuizzer
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        IQuizObject activeQuiz;

        public MainPage()
        {
            this.InitializeComponent();

            activeQuiz = new AdditionQuizObject();
            questionTextBlock.Text = activeQuiz.GetQuestion();
        }

        private void getNextQuestionButton_Click(object sender, RoutedEventArgs e)
        {
            activeQuiz.NextQuestion();
            questionTextBlock.Text = activeQuiz.GetQuestion();
            answerTextBox.Text = "";
            resultTextBlock.Text = "";
        }

        private void checkAnswerButton_Click(object sender, RoutedEventArgs e)
        {
            if (activeQuiz.CheckAnswer(answerTextBox.Text))
            {
                resultTextBlock.Text = "Correct! Well done.";
                Uri soundsource = new Uri("ms-appx:///Sounds/right.wav");
                soundMediaElement.Source = soundsource;
                soundMediaElement.Play();
            }
            else
            {
                resultTextBlock.Text = "Sorry, that is not correct.";
                Uri soundsource = new Uri("ms-appx:///Sounds/wrong.wav");
                soundMediaElement.Source = soundsource;
                soundMediaElement.Play();
            }
        }
    }

如果你们中的某些人可以告诉我我需要为CheckAnswerButton_Click插入事件处理程序以便将Grid的背景更改为SKV_8915_s.jpg,那真是太神奇了!

2 个答案:

答案 0 :(得分:0)

  

如您所见,网格的背景使用名为kingscross.jpg的图像。我试图这样做,以便单击“下一步答案”按钮将导致网格背景更改为名为SKV_8915_s.jpg的图像。

根据您的要求,可以为Grid的Background属性设置ImageBrush,然后将ImageSource与bool属性绑定,如下所示。并使用转换器为每种布尔类型传递不同的图像。

<Grid>
    <Grid.Background>
        <ImageBrush ImageSource="{x:Bind Resault,Converter={StaticResource IMConverter},Mode=OneWay}" Stretch="UniformToFill"/>
    </Grid.Background>
    <Button Content="Check" Click="Button_Click"/>
</Grid>

隐藏代码

public sealed partial class MainPage : Page, INotifyPropertyChanged
{
    public MainPage()
    {
        this.InitializeComponent();
    }
    private bool _resault;

    public event PropertyChangedEventHandler PropertyChanged;
    private void onPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public bool Resault
    {
        get => _resault;
        set
        {
            _resault = value;
            onPropertyChanged();
        }
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        Resault = !Resault;
    }
}
public class ImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        return (bool)value ? new BitmapImage(new Uri("ms-appx:///Assets/bc1.jpg")) : new BitmapImage(new Uri("ms-appx:///Assets/bc2.jpg"));
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

我已经将code sample发布到github上,供您参考。

答案 1 :(得分:0)

感谢小费,但目前这种解决方案超出了我的理解,我对重新设计并不熟悉。但是相反,我找到了一种简单的方法,即进入XAML预览窗口并创建新的图像元素imgbg2。然后,它将让我从后面的代码中进行更改,例如:

  public MainPage()
        {
            this.InitializeComponent();           
        }

        private void Button1_Click(object sender, RoutedEventArgs e)
        {
            //Brush newBackgroundBrushRed = new SolidColorBrush(Colors.Red);           

            if (grid1.Background == newBackgroundBrushImage)
            {
                grid1.Background = bgimg2brush;
            }
else
            {
                grid1.Background = newBackgroundBrushImage;
            }