WPF C# изменить изображение кнопки при наведении - PullRequest
0 голосов
/ 08 апреля 2020

Здравствуйте, я новичок в xaml и c#, и я пытаюсь создать приложение, в котором в списке отображается список объектов. Эта часть работает в основном нормально. Однако я нахожу некоторые проблемы с тем, что моя кнопка настроена (обычно фон изображения меняется при наведении курсора).

У меня проблема с показом кнопки только в последнем элементе списка. Более того, кнопка появляется, если я изменяю свой код во время работы приложения, но если я перезапускаю приложение, тот же код больше не работает.

Наконец, я получаю предупреждение о том, что не могу определить propety об элементе propety в одной из этих 4 строк

<Style TargetType="{x:Type Button}">
                                    <Setter Property="Template">
                                        <Setter.Value>
                                            <ControlTemplate TargetType="Button">

вот код окна xaml (я полагаю, проблема в кнопочной части, поэтому я только помещаю ее, но если вам нужно остальной код просто спросите)

<Button x:Name="sell" BorderThickness="0" Background="Transparent" HorizontalAlignment="Center"  Grid.Row="3" Grid.Column="1" VerticalAlignment="Center"  Grid.ColumnSpan="1" Cursor="Hand" MaxWidth="250">
                            <Button.Style>
                                <Style TargetType="{x:Type Button}">
                                    <Setter Property="Template">
                                        <Setter.Value>
                                            <ControlTemplate TargetType="Button">
                                                <StackPanel Width="{TemplateBinding Width}" Height="{TemplateBinding Width}" x:Name="panel">
                                                    <ContentPresenter Width="{TemplateBinding Width}" Height="68" />
                                                </StackPanel>
                                                <ControlTemplate.Triggers>
                                                    <Trigger Property="IsPressed" Value="true">
                                                        <Setter Property="Background" Value="Transparent" TargetName="panel" />

                                                    </Trigger>
                                                    <Trigger Property="IsMouseOver" Value="true">
                                                        <Setter Property="Background" Value="Transparent" />
                                                        <Setter Property="Content">
                                                            <Setter.Value>
                                                                <Image Source="{Binding lienDeletePressed}"/>
                                                            </Setter.Value>
                                                        </Setter>
                                                    </Trigger>
                                                    <Trigger Property="IsMouseOver" Value="false">
                                                        <Setter Property="Content">
                                                            <Setter.Value>
                                                                <Image Source="{Binding lienDelete}"/>
                                                            </Setter.Value>
                                                        </Setter>
                                                    </Trigger>
                                                </ControlTemplate.Triggers>
                                            </ControlTemplate>
                                        </Setter.Value>
                                    </Setter>
                                </Style>
                            </Button.Style>
                        </Button>

А вот и файл c#

namespace Planet_manager
{
    /// <summary>
    /// Logique d'interaction pour batiments.xaml
    /// </summary>
    public partial class batiments : Window
    {
        public batiments()
        {
            InitializeComponent();
            List<Batiment> listBats = new List<Batiment>();
            listBats.Add(new Batiment() { Nom = "Complexe immobilier", Niveau = 1, img = "/imgs/bats/img_bat1.jpg", Prix_bois = 10, Prix_fer = 10, Prix_or = 0, Prix_petrole = 0, owned=1});
            listBats.Add(new Batiment() { Nom = "Scierie", Niveau = 0, img = "/imgs/bats/img_bat2.jpg", Prix_fer = 10, Prix_or = 1000, Prix_petrole = 0, owned = 1 });
            listBats.Add(new Batiment() { Nom = "Mine de fer", Niveau = 1, img = "/imgs/bats/img_bat3.jpg", Prix_fer = 10, Prix_or = 0, Prix_petrole = 100, owned = 1 });
            listBats.Add(new Batiment() { Nom = "Piscine", Niveau = 1, img = "/imgs/bats/img_bat4.jpg", Prix_fer = 10, Prix_or = 0, Prix_petrole = 0, owned = 1 });
            listBats.Add(new Batiment() { Nom = "Immeuble d'habitation", Niveau = 5, img = "/imgs/bats/img_bat5.jpg", Prix_fer = 10, Prix_or = 0, Prix_petrole = 0, owned = 1 });
            listBats.Add(new Batiment() { Nom = "Caserne", Niveau = 1, img = "/imgs/bats/img_bat6.jpg", Prix_fer = 10, Prix_or = 0, Prix_petrole = 500, owned = 1 });
            listBats.Add(new Batiment() { Nom = "Complexe immobilier", Niveau = 1, img = "/imgs/bats/img_bat1.jpg", Prix_fer = 10, Prix_or = 0, Prix_petrole = 0, owned = 1 });
            listBats.Add(new Batiment() { Nom = "Scierie", Niveau = 5, img = "/imgs/bats/img_bat2.jpg", Prix_fer = 10, Prix_or = 0, Prix_petrole = 0, owned = 1 });
            listBats.Add(new Batiment() { Nom = "Mine de fer", Niveau = 1, img = "/imgs/bats/img_bat3.jpg", Prix_fer = 10, Prix_or = 100000, Prix_petrole = 0, owned = 1 });
            listBats.Add(new Batiment() { Nom = "Piscine", Niveau = 1, img = "/imgs/bats/img_bat4.jpg", Prix_fer = 10, Prix_or = 0, Prix_petrole = 0, owned = 1 });
            listBats.Add(new Batiment() { Nom = "Immeuble d'habitation", Niveau = 1, img = "/imgs/bats/img_bat5.jpg", Prix_fer = 10, Prix_or = 0, Prix_petrole = 0, owned = 1 });
            listBats.Add(new Batiment() { Nom = "Caserne", Niveau = 5, img = "/imgs/bats/img_bat6.jpg", Prix_fer = 10, Prix_or = 0, Prix_petrole = 0, owned = 1 });
            listBats.Add(new Batiment() { Nom = "Complexe immobilier", Niveau = 1, img = "/imgs/bats/img_bat1.jpg", Prix_fer = 10, Prix_or = 0, Prix_petrole = 0, owned = 1 });
            listBats.Add(new Batiment() { Nom = "Scierie", Niveau = 5, img = "/imgs/bats/img_bat2.jpg", Prix_fer = 1000, Prix_or = 0, Prix_petrole = 0, owned = 1 });
            listBats.Add(new Batiment() { Nom = "Mine de fer", Niveau = 10, img = "/imgs/bats/img_bat3.jpg", Prix_fer = 10, Prix_or = 110, Prix_petrole = 1110, owned = 1 });
            listBats.Add(new Batiment() { Nom = "Piscine", Niveau = 10, img = "/imgs/bats/img_bat4.jpg", Prix_fer = 10, Prix_or = 5, Prix_petrole = 0, owned = 1 });

            Jeu j = new Jeu() { Id = 1, Nom_joueur = "samuel", Nom_planete = "novus", Nbre_de_tour = 1, Fer = 10, Or = 10, Bois = 10, Petrole = 0, Argent = 1000, Nbre_de_slot = 0, Nbre_slot_max = 5 };


            foreach (Batiment b in listBats)
            {
                //ajout lien construction-amelioration

                if (b.owned ==1)
                {
                    //cas ou on possède deja le batiment
                    if (b.Prix_bois > j.Bois || b.Prix_fer > j.Fer || b.Prix_or > j.Or || b.Prix_petrole > j.Petrole)
                    {
                        b.lienBuild = "/imgs/ui/buttons/button_améliorer_nope.png";
                        b.lienBuildPressed = "/imgs/ui/buttons/button_améliorer_nope.png";
                    }
                    else
                    {
                        b.lienBuild = "/imgs/ui/buttons/button_améliorer.png";
                        b.lienBuildPressed = "/imgs/ui/buttons/pressed/button_améliorer_pressed.png";

                    }
                }
                else //cas ou on veut construire un batiment
                {
                    if (b.Prix_bois > j.Bois || b.Prix_fer > j.Fer || b.Prix_or > j.Or || b.Prix_petrole > j.Petrole)
                    {
                        b.lienBuild = "/imgs/ui/buttons/button_construire_nope.png";
                        b.lienBuildPressed = "/imgs/ui/buttons/button_construire_nope.png";
                    }
                    else
                    {
                        b.lienBuild = "/imgs/ui/buttons/button_construire.png";
                        b.lienBuildPressed = "/imgs/ui/buttons/pressed/button_construire_pressed.png";
                    }
                }

                //ajout lien destruction
                if (b.owned == 1 )
                {
                    b.lienDelete = "/imgs/ui/buttons/button_detruire.png";
                    b.lienDeletePressed = "/imgs/ui/buttons/pressed/button_detruire_pressed.png";
                }
                else
                {
                    b.lienDelete = "";
                    b.lienDeletePressed = "";
                }


            }

            list_bat.ItemsSource = listBats;
        }


    }


}

спасибо за помощь

вот картинка с результатом при запуске: ошибка печати и вот после того, как я только что удалил сохраненное, затем снова добавил

<Image Source="{Binding lienDeletePressed}"/>

ошибка печати ok

вот код класса batiments по запросу:

class Batiment
    {

        public int Id { get; set; }
        public string Nom { get; set; }
        public string img { get; set; }
        public int Niveau { get; set; }
        public int Ressources_produites { get; set; }
        public int Prix_bois { get; set; }
        public int Prix_fer { get; set; }
        public int Prix_or { get; set; }
        public int Prix_petrole { get; set; }
        public int Quantite_pop { get; set; }
        public int Qualie_pop { get; set; }
        public int owned { get; set; }
        public int prod_pop { get; set; }
        //valeur des liens des boutons construire/ameliorer
        public string lienBuild { get; set; }
        //valeur des liens des boutons detruire
        public string lienDelete { get; set; }
        public string lienBuildPressed { get; set; }
        //valeur des liens des boutons detruire
        public string lienDeletePressed { get; set; }
}

1 Ответ

0 голосов
/ 08 апреля 2020

Я провел несколько других тестов и, наконец, изменил кнопку, и теперь она работает нормально. Единственным недостатком является то, что базовый c "синий системный" цвет кнопки при наведении все еще там, и я не мог сделать код, скрывающий его, не нарушая привязку изображения.


                        <Button x:Name="buy" Tag="{Binding Id}" BorderThickness="0" Background="Transparent" HorizontalAlignment="Center"  Grid.Row="3"  Grid.Column="0" VerticalAlignment="Center"  Grid.ColumnSpan="1" Cursor="Hand" MaxWidth="250" Click="buy_Click" >
                            <Image>
                                <Image.Style>
                                    <Style TargetType="{x:Type Image}">
                                        <Setter Property="Source" Value="{Binding lienBuild}"/>
                                        <Style.Triggers>
                                            <Trigger Property="IsMouseOver" Value="True">
                                                <Setter Property="Source" Value="{Binding lienBuildPressed}"/>
                                            </Trigger>
                                        </Style.Triggers>
                                    </Style>
                                </Image.Style>
                            </Image>
                        </Button>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...