Получение данных из выпадающего списка (в usercontrol) на странице wpf

#wpf #entity-framework #user-controls

#wpf #entity-framework #пользовательские элементы управления

Вопрос:

в приложении WPF я хочу получить данные из выпадающего списка, который находится в пользовательском элементе управления, и передать его текстовому блоку на странице. Обратите внимание, что элементы выпадающего списка привязаны к таблице SQL через EntityFramework. Вот UserControl:

 <UserControl x:Class="TODO_ERP_AGRO.User_Controls.BartenderFormats_CB"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d" 
             d:DesignHeight="35" d:DesignWidth="800">
    <StackPanel Orientation="Horizontal">
        <Label Content="FORMATS BARTENDER"/>
        <ComboBox x:Name="BartFormats_CB" Style="{StaticResource PlainComboBoxStyle}"
                  Width="250" IsEnabledChanged="BartFormats_CB_IsEnabledChanged"/>
    </StackPanel>
</UserControl> 

И .cs пользовательского элемента управления

 using System.Windows;
using System.Windows.Controls;

namespace TODO_ERP_AGRO.User_Controls
{
    /// <summary>
    /// Logique d'interaction pour BartenderFormats_CB.xaml
    /// </summary>
    public partial class BartenderFormats_CB : UserControl
    {
        public BartenderFormats_CB()
        {
            InitializeComponent();
            Sql_Queries.SQLS.GetFormats_Bartender(BartFormats_CB);
        }
        public string BartenderFormat_Name
        {
            get { return BartFormats_CB.SelectedItem.ToString(); }
            set { BartFormats_CB.SelectedItem = value; }
        }

        private void BartFormats_CB_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            switch (((ComboBox)sender).IsEnabled)
            {
                case false:
                    ((ComboBox)sender).SelectedIndex = -1;
                    break;
                default:
                    break;
            }
        }
    }
} 

Привязка выпадающего списка

  public static void GetFormats_Bartender(ComboBox cb)
    {
        using (UTILITAIRESEntities dc = new UTILITAIRESEntities())
        {
            cb.ItemsSource = (from a in dc.VW_BARTENDER_FORMATS
                             orderby a.MODELE_ETIQ
                             select new
                             {
                                 a.ET_NUMSEQ,
                                 a.MODELE_ETIQ
                             }).ToList();
            cb.DisplayMemberPath = "MODELE_ETIQ";
            cb.SelectedValuePath = "ET_NUMSEQ";
            dc.Dispose();
        }
    }
 

И UserContrpl на странице WPF

 <UserControl x:Class="TODO_ERP_AGRO.User_Controls.Create_UC"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:ucs="clr-namespace:TODO_ERP_AGRO.User_Controls"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="1100">
    <Grid Background="{StaticResource SombreBackground}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        
        <!--#region TYPE -->
        <GroupBox Header="TYPE" Style="{StaticResource PlainGroupBoxStyle}">
            <WrapPanel Orientation="Horizontal">
                <RadioButton x:Name="Bartender_RB" Content="BARTENDER"
                             Style="{StaticResource PlainRadioButton_Style}"/>
                <RadioButton x:Name="Crystal_RB" Content="CRYSTAL REPORT"
                             Style="{StaticResource PlainRadioButton_Style}"/>
                <RadioButton x:Name="Autre_RB" Content="Autre"
                             Style="{StaticResource PlainRadioButton_Style}"/>
            </WrapPanel>
        </GroupBox>
        <!--#endregion-->

        <!--#region Details TYPE -->
        <GroupBox Header="DETAILS" Grid.Row="1">
            <WrapPanel Orientation="Horizontal">
                <ucs:BartenderFormats_CB/>
            </WrapPanel>
        </GroupBox>
        <!--#endregion-->
        <StackPanel Grid.Row="2">
            <Button x:Name="Test_Btn" Content="TEST" Click="Test_Btn_Click" Width="50"/>
            <TextBlock x:Name="TestTxtBlock"/>
        </StackPanel>
        

    </Grid>
</UserControl> 

.cs

   private void Test_Btn_Click(object sender, RoutedEventArgs e)
    {
        BartenderFormats_CB cb = new BartenderFormats_CB();
        TestTxtBlock.Text = cb.BartFormats_CB.ToString();
    }
 

Когда я нажимаю на кнопку, ничего не добавляется (ошибок нет).
Спасибо, что помогли мне

Ответ №1:

Когда вы помещаете экземпляр своего usercontrol в окно, вы создаете его экземпляр.

Чтобы получить доступ к его членам, просто присвоите имя usercontrol и используйте его для доступа к его членам.

используйте этот код:

 <GroupBox Header="DETAILS" Grid.Row="1">
    <WrapPanel Orientation="Horizontal">
       <ucs:BartenderFormats_CB x:Name="myCMB"/>
    </WrapPanel>
</GroupBox>
 

и ваш код :

 private void Test_Btn_Click(object sender, RoutedEventArgs e)
{
   TestTxtBlock.Text = myCMB.BartenderFormat_Name;
}