0

Почему listBox выделяется красным ?

xaml

Page x:Class="CompanyApp.View.UserManagementPage"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
  xmlns:local="clr-namespace:CompanyApp.View"
  mc:Ignorable="d" 
  d:DesignHeight="265" d:DesignWidth="497"
  Title="UserManagementPage">

<Grid>
    <ListBox x:Name="listView1" Grid.Column="0" ItemsSource="{Binding CollectionUsers}" 
                 SelectedItem="{Binding SelectmodelUsers}" Margin="10,10,100,10">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel HorizontalAlignment="Left" Width="200" Height="Auto" VerticalAlignment="Top">
                    <TextBlock x:Name="textBlock1" TextWrapping="WrapWithOverflow" FontSize="18" Text ="{Binding InfoUser}"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    <Button x:Name="buttonOpen" Content="Подробнее" HorizontalAlignment="Left" Margin="402,23,0,0" VerticalAlignment="Top" Width="85" Height="25" Click="buttonOpen_Click"/>
    <Button x:Name="buttonEdit" Content="Изменить" HorizontalAlignment="Left" Margin="402,78,0,0" VerticalAlignment="Top" Width="85" Height="25" Click="buttonEdit_Click"/>
    <Button x:Name="buttonDelete" Content="Удалить" HorizontalAlignment="Left" Margin="402,108,0,0" VerticalAlignment="Top" Width="85" Height="25"/>


    <Button x:Name="buttonOpenUser" Content="Клиенты" HorizontalAlignment="Left" Margin="402,158,0,0" VerticalAlignment="Top" Width="85" Height="25" Click="buttonOpenUser_Click"/>
    <Button x:Name="buttonAdd" Content="Добавить" HorizontalAlignment="Left" Margin="402,50,0,0" VerticalAlignment="Top" Width="85" Height="25" Click="buttonAdd_Click"/>
    <Button x:Name="buttonOpenSalesPerson" Content="Продавцы" HorizontalAlignment="Left" Margin="402,188,0,0" VerticalAlignment="Top" Width="85" Height="25" Click="buttonOpenSalesPerson_Click"/>
    <Button x:Name="buttonOpenPartner" Content="Партнёры" HorizontalAlignment="Left" Margin="402,218,0,0" VerticalAlignment="Top" Width="85" Height="25" Click="buttonOpenPartner_Click"/>
</Grid>

Binding

    using System;
using System.Collections.ObjectModel;
using CompanyApp.Model;
using CompanyApp.View;
using System.Data.SqlClient;

namespace CompanyApp.ViewModel
{
    class ApplicationViewModel
    {
        private String connectionString;

        private AdministrativeModelUsers modelUsers;
        private AdministrativeModelSalesPerson modelSalesPerson;
        private AdministrativeModelPartner modelPartner;
        private AdministrativeModelContract modelContract;
        private AdministrativeModelBoat modelBoat;
        private AdministrativeModelAccessory modelAccessory;
        public ObservableCollection<AdministrativeModelUsers> CollectionUsers { get; set; }
        public ObservableCollection<AdministrativeModelSalesPerson> CollectionSalesPerson { get; set; }
        public ObservableCollection<AdministrativeModelPartner> CollectionPartner { get; set; }
        public ObservableCollection<AdministrativeModelContract> CollectionContract { get; set; }
        public ObservableCollection<AdministrativeModelBoat> CollectionBoat { get; set; }
        public ObservableCollection<AdministrativeModelAccessory> CollectionAccessory { get; set; }

        public AdministrativeModelUsers SelectmodelUsers
        {
            get { return modelUsers; }
            set { modelUsers = value; }
        }

        public AdministrativeModelSalesPerson SelectModelSalesPerson
        {
            get { return modelSalesPerson; }
            set { modelSalesPerson = value; }
        }
        public AdministrativeModelPartner SelectModelPartner
        {
            get { return modelPartner; }
            set { modelPartner = value; }
        }
        public AdministrativeModelContract SelectModelContract
        {
            get { return modelContract; }
            set { modelContract = value; }
        }
        public AdministrativeModelBoat SelectModelBoat
        {
            get { return modelBoat; }
            set { modelBoat = value; }
        }
        public AdministrativeModelAccessory SelectModelAccessory
        {
            get { return modelAccessory; }
            set { modelAccessory = value; }
        }

        public ApplicationViewModel()
        {
            connectionString = AuthenticationWindow.connectionString;

            CollectionUsers = new ObservableCollection<AdministrativeModelUsers>();
            CollectionSalesPerson = new ObservableCollection<AdministrativeModelSalesPerson>();
            CollectionPartner = new ObservableCollection<AdministrativeModelPartner>();
            CollectionContract = new ObservableCollection<AdministrativeModelContract>();
            CollectionBoat = new ObservableCollection<AdministrativeModelBoat>();
            CollectionAccessory = new ObservableCollection<AdministrativeModelAccessory>();

            SqlConnection connection = new SqlConnection(connectionString);
            connection.Open();
            //Загрузка клиентов из БД
            using (SqlCommand sqlCommand = new SqlCommand("SELECT RTRIM(Login) as Login, RTRIM(FirstName) as FirstName, RTRIM(FamilyName) as FamilyName, Customer_ID FROM [Customer]", connection))
            {
                using (SqlDataReader dataReader = sqlCommand.ExecuteReader())
                {
                    while (dataReader.Read())
                    {
                        String Login = Convert.ToString(dataReader["Login"]);
                        String FirstName = Convert.ToString(dataReader["FirstName"]);
                        String FamilyName = Convert.ToString(dataReader["FamilyName"]);
                        Int32 id = Convert.ToInt32(dataReader["Customer_ID"]);

                        CollectionUsers.Add(new AdministrativeModelUsers { LoginUser = Login, FirstNameUser = FirstName, FamilyNameUser = FamilyName, IdUser = id });
                    }
                }
            }

            //Загрузка менеджеров из БД
            using (SqlCommand sqlCommand = new SqlCommand("SELECT RTRIM(FirstName) as FirstName, RTRIM(FamilyName) as FamilyName, SalesPerson_ID FROM [SalesPerson]", connection))
            {
                using (SqlDataReader dataReader = sqlCommand.ExecuteReader())
                {
                    while (dataReader.Read())
                    {
                        String FirstName = Convert.ToString(dataReader["FirstName"]);
                        String FamilyName = Convert.ToString(dataReader["FamilyName"]);
                        Int32 Id = Convert.ToInt32(dataReader["SalesPerson_ID"]);

                        CollectionSalesPerson.Add(new AdministrativeModelSalesPerson { FirstName = FirstName, FamilyName = FamilyName, IdPerson = Id });
                    }
                }
            }

            //Загрузка партнёров из БД
            using (SqlCommand sqlCommand = new SqlCommand("SELECT RTRIM(Name) as Name, RTRIM(Address) as Address, RTRIM(City) as City, Partner_ID FROM [Partner]", connection))
            {
                using (SqlDataReader dataReader = sqlCommand.ExecuteReader())
                {
                    while (dataReader.Read())
                    {
                        String Name = Convert.ToString(dataReader["Name"]);
                        String Address = Convert.ToString(dataReader["Address"]);
                        String City = Convert.ToString(dataReader["City"]);
                        Int32 IdPartner = Convert.ToInt32(dataReader["Partner_ID"]);

                        CollectionPartner.Add(new AdministrativeModelPartner { IDPartner = IdPartner, Name = Name, Address = Address, City = City });
                    }
                }
            }
            //Загрузка заказов из БД
            using (SqlCommand sqlCommand = new SqlCommand("SELECT Contract_ID,Date,DepositPayed,Order_ID,ContractTotalPrice,ContracTotalPrice_inclVAT,ProductionProcess FROM [Contract]", connection))
            {
                using (SqlDataReader dataReader = sqlCommand.ExecuteReader())
                {
                    while (dataReader.Read())
                    {
                        Int32 contract_ID = Convert.ToInt32(dataReader["Contract_ID"]);
                        DateTime date = Convert.ToDateTime(dataReader["Date"]);
                        decimal depositPayed = Convert.ToDecimal(dataReader["DepositPayed"]);
                        Int32 order_ID = Convert.ToInt32(dataReader["Order_ID"]);
                        decimal contractTotalPrice = Convert.ToDecimal(dataReader["ContractTotalPrice"]);
                        decimal contracTotalPrice_inclVAT = Convert.ToDecimal(dataReader["ContracTotalPrice_inclVAT"]);
                        Int32 productionProcess = Convert.ToInt32(dataReader["ProductionProcess"]);

                        CollectionContract.Add(new AdministrativeModelContract
                        {
                            ContractID = contract_ID,
                            Date = date,
                            DepositPayed = depositPayed,
                            OrderID = order_ID,
                            ContractTotalPrice = contractTotalPrice,
                            ContracTotalPrice_inclVAT = contracTotalPrice_inclVAT,
                            ProductionProcess = productionProcess
                        });
                    }
                }
            }
            //Загрузка лодок из БД
            using (SqlCommand sqlCommand = new SqlCommand("SELECT boat_ID, RTRIM(Model) as Model, RTRIM(BoatType) as BoatType, " +
                "NumberOfRowers, Mast, RTRIM(Colour) as Colour, RTRIM(Wood) as Wood, BasePrice, VAT" +
                " FROM Boat", connection))
            {
                using (SqlDataReader dataReader = sqlCommand.ExecuteReader())
                {
                    while (dataReader.Read())
                    {
                        Int32 boat_ID = Convert.ToInt32(dataReader["boat_ID"]);
                        String model = Convert.ToString(dataReader["Model"]);
                        String boatType = Convert.ToString(dataReader["BoatType"]);
                        Int32 numberOfRowers = Convert.ToInt32(dataReader["NumberOfRowers"]);
                        Boolean mast = Convert.ToBoolean(dataReader["Mast"]);
                        String colour = Convert.ToString(dataReader["Colour"]);
                        String wood = Convert.ToString(dataReader["Wood"]);
                        decimal basePrice = Convert.ToDecimal(dataReader["BasePrice"]);
                        Int32 vat = Convert.ToInt32(dataReader["VAT"]);

                        CollectionBoat.Add(new AdministrativeModelBoat
                        {
                            Boat_ID = boat_ID,
                            Model = model,
                            BoatType = boatType,
                            NumberOfRowers = numberOfRowers,
                            Mast = mast,
                            Colour = colour,
                            Wood = wood,
                            BasePrice = basePrice,
                            Vat = vat
                        });

                    }
                }
            }
            //Загрузка аксессуаров
            using (SqlCommand sqlCommand = new SqlCommand("SELECT Accessory_ID, RTRIM(AccName) as AccName, " +
                "RTRIM(DescriptionOfAccessory) as Description, Price, VAT, Inventory, " +
                "OrderLevel, OrderBatch, Partner_ID" +
                " FROM [Accessory]", connection))
            {
                using (SqlDataReader dataReader = sqlCommand.ExecuteReader())
                {
                    while (dataReader.Read())
                    {
                        Int32 accessory_ID = Convert.ToInt32(dataReader["Accessory_ID"]);
                        String accName = Convert.ToString(dataReader["AccName"]);
                        String descriptionOfAccessory = Convert.ToString(dataReader["Description"]);
                        decimal price = Convert.ToDecimal(dataReader["Price"]);
                        Int32 vat = Convert.ToInt32(dataReader["VAT"]);
                        Int32 inventory = Convert.ToInt32(dataReader["Inventory"]);
                        Int32 orderLevel = Convert.ToInt32(dataReader["OrderLevel"]);
                        Int32 orderBatch = Convert.ToInt32(dataReader["OrderBatch"]);
                        Int32 partner_ID = Convert.ToInt32(dataReader["Partner_ID"]);

                        CollectionAccessory.Add(new AdministrativeModelAccessory
                        {
                            Accessory_ID = accessory_ID,
                            AccName = accName,
                            DescriptionOfAccessory = descriptionOfAccessory,
                            Price = price,
                            Vat = vat,
                            Inventory = inventory,
                            OrderLevel = orderLevel,
                            OrderBatch = orderBatch,
                            Partner_ID = partner_ID
                        });

                    }
                }
            }

            connection.Close();
        }

    }
}

Обработка

    using CompanyApp.ViewModel;
using CompanyApp.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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 CompanyApp.View
{
    /// <summary>
    /// Логика взаимодействия для UserManagementPage.xaml
    /// </summary>
    public partial class UserManagementPage : Page
    {
        public UserManagementPage()
        {
            InitializeComponent();
            DataContext = new ApplicationViewModel();
        }

        private void buttonOpen_Click(object sender, RoutedEventArgs e)
        {
            if (listView1.SelectedItem != null)
            {
                if (listView1.SelectedItem is AdministrativeModelUsers)
                {
                    AdministrativeModelUsers name = listView1.SelectedItem as AdministrativeModelUsers;
                    UserInfoWindow window = new UserInfoWindow(name);
                    window.ShowDialog();
                }else if(listView1.SelectedItem is AdministrativeModelSalesPerson)
                {
                    AdministrativeModelSalesPerson name = listView1.SelectedItem as AdministrativeModelSalesPerson;
                    UserInfoWindow window = new UserInfoWindow(name);
                    window.ShowDialog();
                }
                else if (listView1.SelectedItem is AdministrativeModelPartner)
                {
                    AdministrativeModelPartner name = listView1.SelectedItem as AdministrativeModelPartner;
                    UserInfoWindow window = new UserInfoWindow(name);
                    window.ShowDialog();
                }
            }
        }

        private void buttonOpenUser_Click(object sender, RoutedEventArgs e)
        {
            listView1.ItemsSource = new ApplicationViewModel().CollectionUsers;
            listView1.SelectedItem = new ApplicationViewModel().SelectmodelUsers;
        }

        private void buttonOpenSalesPerson_Click(object sender, RoutedEventArgs e)
        {
            listView1.ItemsSource = new ApplicationViewModel().CollectionSalesPerson;
            listView1.SelectedItem = new ApplicationViewModel().SelectModelSalesPerson;
        }

        private void buttonOpenPartner_Click(object sender, RoutedEventArgs e)
        {
            listView1.ItemsSource = new ApplicationViewModel().CollectionPartner;
            listView1.SelectedItem = new ApplicationViewModel().SelectModelPartner;
        }

        private void buttonEdit_Click(object sender, RoutedEventArgs e)
        {
            if (listView1.SelectedItem != null)
            {
                if (listView1.SelectedItem is AdministrativeModelUsers)
                {
                    AdministrativeModelUsers name = listView1.SelectedItem as AdministrativeModelUsers;
                    EditWindow window = new EditWindow(name);
                    window.ShowDialog();
                }
                else if (listView1.SelectedItem is AdministrativeModelSalesPerson)
                {
                    AdministrativeModelSalesPerson name = listView1.SelectedItem as AdministrativeModelSalesPerson;
                    EditWindow window = new EditWindow(name);
                    window.ShowDialog();
                }
                else if (listView1.SelectedItem is AdministrativeModelPartner)
                {
                    AdministrativeModelPartner name = listView1.SelectedItem as AdministrativeModelPartner;
                    EditWindow window = new EditWindow(name);
                    window.ShowDialog();
                }
            }
        }

        private void buttonAdd_Click(object sender, RoutedEventArgs e)
        {
            RegistrationWindow window = new RegistrationWindow();
            window.ShowDialog();
        }
    }
}

listbox

xaml

button Продавцы

OUTPUT

System.Windows.Data Error: 23 : Cannot convert 'CompanyApp.Model.AdministrativeModelSalesPerson' from type 'AdministrativeModelSalesPerson' to type 'CompanyApp.Model.AdministrativeModelUsers' for 'en-US' culture with default conversions; consider using Converter property of Binding. NotSupportedException:'System.NotSupportedException: TypeConverter не может выполнить преобразование из CompanyApp.Model.AdministrativeModelSalesPerson. в System.ComponentModel.TypeConverter.GetConvertFromException(Object value) в System.ComponentModel.TypeConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value) в MS.Internal.Data.DefaultValueConverter.ConvertHelper(Object o, Type destinationType, DependencyObject targetElement, CultureInfo culture, Boolean isForward)' System.Windows.Data Error: 7 : ConvertBack cannot convert value 'CompanyApp.Model.AdministrativeModelSalesPerson' (type 'AdministrativeModelSalesPerson'). BindingExpression:Path=SelectmodelUsers; DataItem='ApplicationViewModel' (HashCode=45492604); target element is 'ListBox' (Name='listView1'); target property is 'SelectedItem' (type 'Object') NotSupportedException:'System.NotSupportedException: TypeConverter не может выполнить преобразование из CompanyApp.Model.AdministrativeModelSalesPerson. в MS.Internal.Data.DefaultValueConverter.ConvertHelper(Object o, Type destinationType, DependencyObject targetElement, CultureInfo culture, Boolean isForward) в MS.Internal.Data.ObjectTargetConverter.ConvertBack(Object o, Type type, Object parameter, CultureInfo culture) в System.Windows.Data.BindingExpression.ConvertBackHelper(IValueConverter converter, Object value, Type sourceType, Object parameter, CultureInfo culture)'

12
  • 1
    А почему не должен выделяться красным? Смотрите ваши стили, смотрите куда вставляете ваш контрол
    – tym32167
    1 фев 2018 в 10:42
  • @tym32167, мне нужно, что бы listBox не выделялся. Так как если нажимать на "клиенты" то не выделяется, а как только происходит нажатие на "Продавцы, Партнёры" то выделяется. Код тот же, и я не понимаю почему так происходит.
    – TexnikBy
    1 фев 2018 в 10:50
  • Подозреваю что это как-то связано с валидацией, но пока не понятно как 1 фев 2018 в 10:55
  • Я бы сказал, того, что показано в вопросе, драматически не хватает даже для определения проблемы. И вставьте пожалуйста код текстом, а не картинкой
    – tym32167
    1 фев 2018 в 10:57
  • Где находится ваш CollectionUsers на который вы биндитесь, в ViewModel или в CodeBehind'e?
    – user206435
    1 фев 2018 в 10:58

2 ответа 2

0

Попробуйте так задать стиль по-умолчанию:

<ListBox Style="{x:Null}"></ListBox>
2
  • не помогло, всё равно выделяется. (Клиенты не выделяются, а Продавцы и Партнёры выделяются)
    – TexnikBy
    1 фев 2018 в 10:55
  • 1
    Ну это же костыль. У автора где то есть неправильный стиль, а вы предлагает его просто местно занулить.
    – tym32167
    1 фев 2018 в 10:55
0

Выделение убралось после удаления строки: SelectedItem="{Binding ...}"

введите сюда описание изображения

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.