C#/XAML 将图像添加到按钮

Posted

技术标签:

【中文标题】C#/XAML 将图像添加到按钮【英文标题】:C#/XAML add image to button 【发布时间】:2012-11-21 23:44:36 【问题描述】:

我开始在 Windows Phone 8 中使用 C#/XAML 进行编程。目前我正在开发一个测验类型的 WP8 应用程序,它有一个问题(文本块)和 4 个选项(以按钮的形式)。我想做的是,在按钮中显示这些选项的图像。我要怎么做?

请检查我开始的内容 这是我的 DataEntry 类:

    class DataEntry

    List<DataModel> dataModelList = new List<DataModel>();
    public List<DataModel> GetData()
    
        dataModelList.Add(new DataModel  ID = 0, Question = "A major", Answer1 = "chords/g_major.gif", Answer2 = "chords/c_major.gif", Answer3 = "chords/b_major.gif", CorrectAnswer = "chords/a_major.gif" );
        dataModelList.Add(new DataModel  ID = 1, Question = "B major", Answer1 = "chords/g_major.gif", Answer2 = "chords/d_major.gif", Answer3 = "chords/e_major.gif", CorrectAnswer = "chords/b_major.gif" );
    

还有我的 MainPage 类:

public partial class MainPage : PhoneApplicationPage

    List<DataModel> dataModelList = new List<DataModel>();
    List<ScoreModel> scoreModelList = new List<ScoreModel>();
    Random rand = new Random();
    DataEntry dataEntry = new DataEntry();
    int number1, number2, number3, number4, score = 0, scoreToHave = 4;
    string CorrectAnswer;
    int QuestionID = 0;

    public MainPage()
    
        InitializeComponent();
        dataModelList = dataEntry.GetData();
        Question();
    

    private void Question()
    

        foreach (var item in dataModelList)
        
            if (item.ID == QuestionID)
            
                TextBlock_Question.Text = item.Question;
                CorrectAnswer = item.CorrectAnswer;
                RandomAnswerPlaces(item.Answer1, item.Answer2, item.Answer3, item.CorrectAnswer);
            
        
    

    public void RandomAnswerPlaces(string Answer1, string Answer2, string Answer3, string Answer4)
    
        String[] Answers = new string[4];
        noRepeat();
        Answers[number1] = Answer1;
        Answers[number2] = Answer2;
        Answers[number3] = Answer3;
        Answers[number4] = Answer4;
        btnAnswer1.Content = Answers[0];
        btnAnswer2.Content = Answers[1];
        btnAnswer3.Content = Answers[2];
        btnAnswer4.Content = Answers[3];
    

    private void noRepeat()
    
        number1 = rand.Next(0, 4);
        number2 = rand.Next(0, 4);
        number3 = rand.Next(0, 4);
        number4 = rand.Next(0, 4);
        if (number1 == number2 ||
            number1 == number3 ||
            number1 == number4 ||
            number2 == number3 ||
            number2 == number4 ||
            number3 == number4)
        
            noRepeat();
        
    

    private void btnStartGame(object sender, RoutedEventArgs e)
    
        Canvas_StartGame.Visibility = System.Windows.Visibility.Collapsed;
        Canvas_Game.Visibility = System.Windows.Visibility.Visible;
    

    private void Button_AnswerClick(object sender, RoutedEventArgs e)
    
        string ClickedAnswer = ((System.Windows.Controls.Button)(sender)).Content.ToString();
        string ClickedButtonName = ((System.Windows.Controls.Button)(sender)).Name.ToString();

        switch (ClickedButtonName)
        
            case "btnAnswer1":
                btnAnswer1.IsEnabled = false;
                break;
            case "btnAnswer2":
                btnAnswer2.IsEnabled = false;
                break;
            case "btnAnswer3":
                btnAnswer3.IsEnabled = false;
                break;
            case "btnAnswer4":
                btnAnswer4.IsEnabled = false;
                break;
            default:
                break;
        
        if (CorrectAnswer == ClickedAnswer)
        
            if (QuestionID < (dataModelList.Count() - 1))
            
                QuestionID++;
            
            else
            
                MessageBox.Show(string.Format("Game Over! your final score : 0", score));
                SaveHighScore();
            

            score += scoreToHave;
            scoreToHave = 5;
            Question();
            btnAnswer1.IsEnabled = true;
            btnAnswer2.IsEnabled = true;
            btnAnswer3.IsEnabled = true;
            btnAnswer4.IsEnabled = true;
        
        else
        
            scoreToHave -= 2;
        
        TextBlock_ScoreToHave.Text = string.Format("Score you can get: 0", scoreToHave.ToString());
        TextBlock_Score.Text = string.Format("Score: 0", score.ToString());
    

    private void SaveHighScore()
    
        if (IsolatedStorageSettings.ApplicationSettings.Contains("scoreList"))
        
            scoreModelList = IsolatedStorageSettings.ApplicationSettings["scoreList"] as List<ScoreModel>;
            scoreModelList.Add(new ScoreModel  Score = score, DateSaved = DateTime.Now.ToShortDateString() );
            IsolatedStorageSettings.ApplicationSettings.Clear();
            IsolatedStorageSettings.ApplicationSettings.Add("scoreList", scoreModelList);
            IsolatedStorageSettings.ApplicationSettings.Save();
        
        Canvas_StartGame.Visibility = System.Windows.Visibility.Collapsed;
        Canvas_Game.Visibility = System.Windows.Visibility.Collapsed;
        Canvas_HighScore.Visibility = System.Windows.Visibility.Visible;
        var tempList =
           from item in scoreModelList
           where item.Score > 0
           orderby item.Score descending
           select string.Format("Date: 0 Score: 1", item.DateSaved, item.Score);
        ListBox_HighScore.ItemsSource = tempList.ToList();
        score = 0;
        scoreToHave = 5;
        QuestionID = 0;
        Canvas_StartGame.Visibility = System.Windows.Visibility.Visible;
        Canvas_Game.Visibility = System.Windows.Visibility.Collapsed;
    

    private void Button_DoneClick(object sender, RoutedEventArgs e)
    
        Canvas_StartGame.Visibility = System.Windows.Visibility.Visible;
        Canvas_Game.Visibility = System.Windows.Visibility.Collapsed;
        Canvas_HighScore.Visibility = System.Windows.Visibility.Collapsed;
    

我的 xaml 片段:

<Canvas Name="Canvas_Game" 
            VerticalAlignment="Center"
            HorizontalAlignment="Center" 
            Height="800" Width="480"
            Visibility="Collapsed">
        <!--Visibility="Collapsed">-->
        <Grid  Height="800" Width="480">
            <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
                <TextBlock Name="TextBlock_ScoreToHave" Text="Score to have:"/>
                <TextBlock Name="TextBlock_Score" Text="Score:"/>
                <TextBlock Width="480" Text="Question:" FontSize="40"/>
                <TextBlock VerticalAlignment="Top" Name="TextBlock_Question" Text="What is the meaning of life?" FontSize="32" Width="480" TextAlignment="Left" TextWrapping="Wrap" MaxHeight="400"/>
                <Button Name="btnAnswer1"  Content="Answer1" Click="Button_AnswerClick"/>
                <Image Source="/chords/"></Image>
                <Button Name="btnAnswer2"  Content="Answer2" Click="Button_AnswerClick"/>
                <Button Name="btnAnswer3"  Content="Answer3" Click="Button_AnswerClick"/>
                <Button Name="btnAnswer4"  Content="Answer4" Click="Button_AnswerClick"/>



            </StackPanel>
        </Grid>
    </Canvas>

如您所见,到目前为止我所做的只是在按钮中显示字符串(答案)。我想知道如何显示我从和弦文件夹中调用的图像。任何帮助表示赞赏。谢谢。

【问题讨论】:

您正在为按钮 Content 属性分配一个字符串,您应该创建一个 Image 控件的实例(我不知道 Windows-Phone-8 的命名空间,谷歌它)并分配它到按钮的内容。 【参考方案1】:

尝试以下方法:

<Button Name="btnAnswer4" Click="Button_AnswerClick">
<Image Source="chords/image.png"></Image>
</Button>

我不知道添加Content="Answer4" 是否会在图片上显示文字。

【讨论】:

“随机”部分由您的 ViewModel 实现。只需对 Source 属性使用 Binding。 @HenkHolterman 抱歉,能否请您提供一些绑定源属性的示例,谢谢。新手在这里。 它的工作谢谢!现在我想从 C# 代码中动态更改按钮图像怎么办?? 它的工作谢谢!现在我想从 C# 代码中动态更改按钮图像怎么办??【参考方案2】:

这是我发现的一种将图像添加到按钮的漂亮方法 (from this website)。将您的图像源设置为图像的位置。 (这可以在代码隐藏中完成,因为您的具体问题需要。)

<Button Height="26" Width="26" Cursor="Hand">
    <Button.Template>
        <ControlTemplate>
            <Image Source="Resources/OpenFolder_64x.png"/>
        </ControlTemplate>
    </Button.Template>
</Button>

【讨论】:

【参考方案3】:

如果你想要一个圆形按钮,我建议使用http://coding4fun.codeplex.com/ 及其支持设置 ImagePath 的 RoundButton。 http://coding4fun.codeplex.com/wikipage?title=RoundButton&referringTitle=Documentation

【讨论】:

以上是关于C#/XAML 将图像添加到按钮的主要内容,如果未能解决你的问题,请参考以下文章

通过 XAML 将图像设置为按钮背景

C#/XAML - 字符串到图像源的转换

在 XAML 中创建按钮

图像不显示XAML android

如何通过对话框将图像上传到 SQLite 数据库,并将图像输出到 XAML?

Android将图像添加到数据库