Гость
Форумы / WPF, Silverlight [игнор отключен] [закрыт для гостей] / Combobox+ DataTemplateSelector / 11 сообщений из 11, страница 1 из 1
04.08.2017, 19:06
    #39500489
vb_sub
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Combobox+ DataTemplateSelector
Всем привет, пишу combobox следующего вида:
Код: xml
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
185.
186.
187.
188.
189.
190.
191.
192.
193.
194.
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
205.
206.
207.
208.
209.
210.
211.
212.
213.
214.
215.
216.
217.
218.
219.
220.
221.
222.
223.
224.
225.
226.
227.
228.
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:BaseApp.Styles"
                    xmlns:root="clr-namespace:BaseApp">


    <ControlTemplate x:Key="ComboBoxToggleButton"
               TargetType="{x:Type ToggleButton}">
        <Grid >
            <Grid.ColumnDefinitions>
                <ColumnDefinition />
            </Grid.ColumnDefinitions>

            <Border x:Name="Border"
            Grid.ColumnSpan ="2"
            BorderThickness="1"
            BorderBrush="White"  
            Margin="10 5 10 5"        
            Background="Transparent" />

            <Border Grid.Column="0"
            Margin="1" Background="Transparent"   />

        </Grid>
    </ControlTemplate>


    <ControlTemplate x:Key="ComboBoxTextBox"
                 TargetType="{x:Type TextBox}">

        <Border x:Name="PART_ContentHost"
            Focusable="False"
        Background="{TemplateBinding Background}" />
    </ControlTemplate>



    <Style x:Key="OrderCombobox" TargetType="{x:Type ComboBox}">
        <Style.Resources>
            <Style TargetType="{x:Type TextBlock}">
                <Setter Property="FontSize"  Value="40" />
            </Style>

            <DataTemplate x:Key="selectedTemplate">
            
                <TextBox   Text="{Binding applicant_name}" />
            </DataTemplate>

            
            
            <DataTemplate x:Key="dropDownTemplate">
                <DataTemplate.Resources>
                    <Style  TargetType="{x:Type TextBlock}">
                        <Setter Property="FontSize" Value="20"/>
                        <Setter Property="HorizontalAlignment"  Value="Center"/>
                        <Setter Property="Foreground" Value="White"/>
                        <Setter Property="Margin" Value="5"/>
                        <Setter Property="SnapsToDevicePixels" Value="true" />
                    </Style>
                </DataTemplate.Resources>

                <Border BorderBrush="Cornsilk" BorderThickness="1" Margin="5">
                    <Grid Background="#727A7A7A">
                        <Grid.RowDefinitions>
                            <RowDefinition/>
                            <RowDefinition/>
                            <RowDefinition/>
                        </Grid.RowDefinitions>

                        <Grid.ColumnDefinitions>
                            <ColumnDefinition/>
                            <ColumnDefinition/>
                        </Grid.ColumnDefinitions>

                        <TextBlock Grid.Row="0" Grid.Column="0" Text="{Binding applicant_name}" />
                        <Border 
                             BorderThickness="0 2 0 0"
                             Height="6"
                             Grid.ColumnSpan ="2"
                             Grid.Row="1"
                             VerticalAlignment="Center" BorderBrush="Gray" 
                             Margin="10 0 10 0">
                        </Border>

                        <TextBlock Grid.Row="2"
                                       Grid.Column="1" 
                                       Text="{Binding applicant_departament}" Foreground="GreenYellow" />
                    </Grid>
                </Border>
            </DataTemplate>
        </Style.Resources>


        <Setter Property="SnapsToDevicePixels" Value="true"/>
        <Setter Property="OverridesDefaultStyle" Value="true"/>
        <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto"/>
        <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>
        <Setter Property="ScrollViewer.CanContentScroll" Value="true"/>
        <Setter Property="MinWidth" Value="80"/>
        <Setter Property="MinHeight" Value="20"/>
        <Setter Property="IsEditable" Value="True" />
     

        <!--<Setter Property="IsReadOnly"  Value="False" />-->

        
        <Setter Property="ItemTemplateSelector" >
            <Setter.Value>
                <root:ApplicantTemplateSelector/>
            </Setter.Value>
        </Setter>

        
        
        
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ComboBox">
                    <Grid>
                          <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="Normal" />
                                <VisualState x:Name="MouseOver" />
                                <VisualState x:Name="Disabled">
                                    <Storyboard>
                                        <ColorAnimationUsingKeyFrames Storyboard.TargetName="PART_EditableTextBox"      Storyboard.TargetProperty="(TextElement.Foreground).(SolidColorBrush.Color)">
                                            <EasingColorKeyFrame KeyTime="0"   Value="Green" />
                                        </ColorAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>

                            <VisualStateGroup x:Name="EditStates">
                                <VisualState x:Name="Editable">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="PART_EditableTextBox">
                                            <DiscreteObjectKeyFrame KeyTime="0"     Value="{x:Static Visibility.Visible}" />
                                        </ObjectAnimationUsingKeyFrames>

                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)"     Storyboard.TargetName="ContentSite">
                                            <DiscreteObjectKeyFrame KeyTime="0"
                                            Value="{x:Static Visibility.Hidden}" />
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>

                                <VisualState x:Name="Uneditable" />
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                                           
                        <ToggleButton 
                        Name="ToggleButton" 
                        Template="{StaticResource ComboBoxToggleButton}"
                        Grid.Column="2" />

                        <ContentPresenter
                        Name="ContentSite"
                        IsHitTestVisible="False"                             
                        VerticalAlignment="Center"
                        HorizontalAlignment="Center"  />

                        <!--Content="{TemplateBinding SelectionBoxItem}"
                        ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}"
                        ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}"-->

                  <TextBox x:Name="PART_EditableTextBox"
                   Style="{x:Null}"
                   Template="{StaticResource ComboBoxTextBox}"
                   FontSize="20"
                   Foreground="White"          
                   Focusable="True"
                   VerticalAlignment="Center" 
                   HorizontalAlignment="Center" 
                   Background="Transparent"
                   Visibility="Hidden"
                   IsReadOnly="{TemplateBinding IsReadOnly}" />

                        <Popup     
                        Name="Popup"
                        Placement="Bottom"    
                        IsOpen="{TemplateBinding IsDropDownOpen}"
                        AllowsTransparency="True" 
                        Focusable="False"
                        PopupAnimation="Slide">

                        <Grid    
                          Name="DropDown"
                          SnapsToDevicePixels="True"                
                          MinWidth="{TemplateBinding ActualWidth}"
                          MaxHeight="{TemplateBinding MaxDropDownHeight}">

                                <ScrollViewer Margin="4,0,0,0" SnapsToDevicePixels="True">
                                    <StackPanel IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Contained" />
                                </ScrollViewer>
                            </Grid>
                            
                        </Popup>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    
    </Style>


    <Style TargetType="{x:Type ToggleButton}">
        <Setter Property="Background" Value="Transparent" />
        <Setter Property="Focusable" Value="False"/>
        <Setter Property="ClickMode" Value="Press"/>
        <Setter Property="IsChecked"  Value="{Binding Path=IsDropDownOpen,Mode=TwoWay,RelativeSource={RelativeSource TemplatedParent}}"/>
        <Setter Property="OverridesDefaultStyle" Value="true" />
    </Style>

    <Style TargetType="{x:Type ComboBoxItem}">
        <Setter Property="OverridesDefaultStyle" Value="true" />

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ComboBoxItem}">
                    <ContentPresenter />
                </ControlTemplate>
            </Setter.Value>

        </Setter>

    </Style>
    
</ResourceDictionary>



Селектор шаблона:
Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
public class ApplicantTemplateSelector : DataTemplateSelector
    {
        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            ContentPresenter presenter = (ContentPresenter)container;

            if (presenter.TemplatedParent is ComboBox)
            {
                return (DataTemplate)presenter.FindResource("selectedTemplate");
            }
            else // Templated parent is ComboBoxItem
            {
                return (DataTemplate)presenter.FindResource("dropDownTemplate");
            }

        }

    }



сам комбик:

Код: xml
1.
2.
3.
           <ComboBox 
                          ItemsSource="{Binding Path=list_applicant}">
                </ComboBox>



list_applicant -это List из

Код: c#
1.
2.
3.
4.
5.
  public class applicant
    {
        public string applicant_name { get; set; }
        public string applicant_departament { get; set; }
    }



Проблема в том, что при выборе из выпадающего списка элемента в PART_EditableTextBox отображается экземпляр класса applicant и его дефолтный метод ToString() и я не могу найти где указать Binding Path, чтобы отображалось свойство класса applicant_name. Подскажите плиз кто в курсе.
...
Рейтинг: 0 / 0
04.08.2017, 19:06
    #39500490
vb_sub
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Combobox+ DataTemplateSelector
...
Рейтинг: 0 / 0
04.08.2017, 20:51
    #39500531
iMrTidy
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Combobox+ DataTemplateSelector
vb_sub,

Код: c#
1.
DisplayMemberPath = "applicant_name"
...
Рейтинг: 0 / 0
07.08.2017, 09:52
    #39501093
vb_sub
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Combobox+ DataTemplateSelector
iMrTidy,
к сожалению не то- в простом случае это отработало бы, а при редактированном шаблоне нужно видимо в другом месте искать ошибку.
...
Рейтинг: 0 / 0
07.08.2017, 10:00
    #39501099
vb_sub
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Combobox+ DataTemplateSelector
Почему то когда я ставлю свойство IsEditable =false, все отображается нормально и при выборе элемента код попадает в ApplicantTemplateSelector , но когда я выставляю IsEditable =true, то при выборе элемента из списка брекпоинт в ApplicantTemplateSelector не срабатывает- это при
Код: xml
1.
2.
3.
4.
5.
6.
7.
8.
   <ContentPresenter
                        Name="ContentSite"
                        IsHitTestVisible="False"                             
                        VerticalAlignment="Center"
                        HorizontalAlignment="Center" 
                        Content="{TemplateBinding SelectionBoxItem}"
                        ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}"
                        ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}"  />
...
Рейтинг: 0 / 0
09.08.2017, 11:29
    #39502421
maratoss
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Combobox+ DataTemplateSelector
vb_sub,
как вариант можешь заоверрайдить ToString() и вернуть там applicant_name
...
Рейтинг: 0 / 0
09.08.2017, 11:31
    #39502425
maratoss
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Combobox+ DataTemplateSelector
А вообще в чем задумка что пытаешься сделать?
...
Рейтинг: 0 / 0
09.08.2017, 13:12
    #39502531
vb_sub
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Combobox+ DataTemplateSelector
на крайний случай перепишу ToString конечно.
Проект задумки:
Комбобокс с возможностью ввода текста, при котором фильтруются элементы списка dropdown по определённому полю (с этим пока сложностей нет). В качестве шаблона списка используется своя модель например как на рисунке.
При выборе элемента из списка в TextBox, который используется для ввода фильтрующего значения, должно отобразиться свойство выбранной модели (applicant)(просто строковое значение)+ нужно запомнить, какая модель из списка была выбрана (это я тоже думаю, что проблем не будет). как-то так
...
Рейтинг: 0 / 0
09.08.2017, 13:36
    #39502553
Roman Mejtes
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Combobox+ DataTemplateSelector
нужно просто 2 TextBox'а, 1 который будет отображать значение, а 2ой фильтровать список
если комбик открыт показываешь 2, если закрыт 1
...
Рейтинг: 0 / 0
10.08.2017, 12:14
    #39503259
vb_sub
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Combobox+ DataTemplateSelector
Roman Mejtes,
и с 1 TextBox фильтрация работает. Проблема как раз в том, чтобы этому TextBox указать, какое свойство модели брать.
...
Рейтинг: 0 / 0
27.09.2017, 08:17
    #39526847
vb_sub
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Combobox+ DataTemplateSelector
В итоге оказалось нужно поставить в свойствах комбобокса
TextSearch.TextPath="applicant_name"
...
Рейтинг: 0 / 0
Форумы / WPF, Silverlight [игнор отключен] [закрыт для гостей] / Combobox+ DataTemplateSelector / 11 сообщений из 11, страница 1 из 1
Целевая тема:
Создать новую тему:
Автор:
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]