0

Здравствуйте помогите пожалуйста понять как сделать следующее (Только знакомлюсь с WPF):

Есть N-ое количество папок, в которых расположены некоторые файлы. Один из них это картинка.

Нужно вывести через цикл кнопки в количестве равному количеству папок(лучше всего в grid по 5 в строке) и соответственно необходим скролл, для того что бы можно было листать если количество кнопок не влезает в окно целиком. Всё это нужно засунуть в grid с двумя столбцами. левый для кнопок, а правый для картинки(при наведении на любую из кнопок должна появиться картинка из соответствующей папки)

Допустим как зациклено создать кнопки, я разобрался


C#

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections;
using System.Windows.Navigation;

namespace Conceptor5._0 { public partial class VU : Window { public static string Tematic = ""; public VU() { InitializeComponent();

    Button[] btns = new Button[10];
    for (int i = 0; i < btns.Length; i++)
    {
        var btn = new Button
        {
            Content = "Button-" + i.ToString(),


        };
        btnsPanel.Children.Add(btn);
        btn.Click += new RoutedEventHandler(btn_Click);

    }

}
void btn_Click(object sender, RoutedEventArgs e)
{

    Button buttonThatWasClicked = (Button)sender;
    MessageBox.Show("Button pressed " + buttonThatWasClicked.Content);

}
private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    MainWindow win2 = new MainWindow();
    win2.Show();
    this.Close();
}


}

}

Xalm

<Window x:Class="Conceptor5._0.VU"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Conceptor5._0"
    mc:Ignorable="d"
     Title="MainWindow" Height="450" Width="800"
WindowState="Maximized"
WindowStyle="None" ResizeMode="NoResize" Loaded="Window_Loaded">
<Window.Background>
    <ImageBrush ImageSource="interface\background\Background.jpg"/>
</Window.Background>
<StackPanel>
    <Image Height="100" Width="267" MouseLeftButtonDown="Image_MouseLeftButtonDown"
        Cursor="Hand" HorizontalAlignment="Left" >
        <Image.Style>
            <Style TargetType="{x:Type Image}">
                <Style.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Source" Value="pack://application:,,,/Resources/button_nazad (1).png"/>
                    </Trigger>
                    <Trigger Property="IsMouseOver" Value="False">
                        <Setter Property="Source" Value="pack://application:,,,/Resources/button_nazad.png"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Image.Style>
    </Image>
    <StackPanel>
        <Grid Height="100">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="267*" />
                <ColumnDefinition Width="133*" />
            </Grid.ColumnDefinitions>
            <StackPanel Name="btnsPanel">
        &lt;/StackPanel&gt;
        &lt;Image Grid.Column=&quot;1&quot; Height=&quot;100&quot; Width=&quot;267&quot; Source=&quot;/Resources/test.jpg&quot; &gt;

        &lt;/Image&gt;

    &lt;/Grid&gt;
&lt;/StackPanel&gt;




</StackPanel>

Но даже так, при запуске картинка не появляется


запущенное

При этом в редакторе картинка имеется


Редактор

Вот такой результат я хочу получить


Желаемое

Пожалуйста, помогите разобраться с данным вопросом. И если будет возможность на примере. Заранее спасибо

  • Неправильно вы знакомитесь с WPF, вот так надо. По другим механикам здесь тоже информации полно, надо только поискать. – aepot Aug 23 '22 at 05:57

1 Answers1

0

Свой вопрос я решил полностью. Спасибо за ссылку товарищу с ником aepot.

Ниже привожу решение которое мне подошло (естественно нулевик, чтоб если потребуется другим, было проще разобраться)

Xalm

<Window x:Class="Testmassiv.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Testmassiv"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800"
     d:DataContext="{d:DesignInstance local:MainWindow}">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <StackPanel Orientation="Horizontal">
        <TextBlock Text="Width:" Margin="5" FontWeight="Bold"/>
        <TextBox Width="100" Margin="5" MaxLength="2" Text="{Binding Width, UpdateSourceTrigger=PropertyChanged}"/>
        <TextBlock Text="Height:" Margin="5" FontWeight="Bold"/>
        <TextBox Width="100" Margin="5" MaxLength="2" Text="{Binding Height, UpdateSourceTrigger=PropertyChanged}"/>
    </StackPanel>
    <ItemsControl ItemsSource="{Binding Items}" Grid.Row="1" >
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Border BorderThickness="4" BorderBrush="#add8e6" Margin="3">
                    <Button x:Name="bq" Content="{Binding}" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" FontSize="20" Click="Button_Click" MouseLeftButtonDown="bq_MouseLeftButtonDown">
                        <Button.Background>
                            <ImageBrush ImageSource="/Background.jpg" Stretch="Fill"/>
                        </Button.Background>
                    </Button>
            &lt;/Border&gt;
        &lt;/DataTemplate&gt;
    &lt;/ItemsControl.ItemTemplate&gt;
    &lt;ItemsControl.ItemsPanel&gt;
        &lt;ItemsPanelTemplate&gt;
            &lt;UniformGrid Rows=&quot;{Binding Height}&quot; Columns=&quot;{Binding Width}&quot;/&gt;
        &lt;/ItemsPanelTemplate&gt;
    &lt;/ItemsControl.ItemsPanel&gt;
&lt;/ItemsControl&gt;

</Grid>

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Testmassiv {

public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext = new MainWindowViewModel(); }

private void Button_Click(object sender, RoutedEventArgs e)
{

    if (Content.ToString() != null)
    {
        var senderBtn = sender as Button;
        MessageBox.Show(senderBtn.Content.ToString());
    }

}


} }

Class View model

using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;

public class MainWindowViewModel : INotifyPropertyChanged { private int width; private int height;

public event PropertyChangedEventHandler PropertyChanged;

private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); }

public int Width { get => width; set { width = value; OnPropertyChanged(nameof(Width)); OnPropertyChanged(nameof(Items)); } }

public int Height { get => height; set { height = value; OnPropertyChanged(nameof(Height)); OnPropertyChanged(nameof(Items)); } }

public IEnumerable<string> Items => Directory.EnumerateDirectories("C:\Users\verma\source\repos\ForConcept").Select(System.IO.Path.GetFileName);

}

На дизайн прошу не реагировать, все ради теста 1 2 3 4

Что касаемо вопроса, вывода отдельной картинки то Grid в Grid. Еще раз спасибо aepot-у и надеюсь тема кому-то поможет