Привязка шаблонов не работает с командой WPF

#c# #wpf #mvvm #data-binding

#c# #wpf #mvvm #привязка данных

Вопрос:

В настоящее время я работаю над новым выпадающим списком, в котором есть кнопка под названием «Добавить», которая должна запускать команду при нажатии, в основном это запустит новое окно для добавления новой строки в базу данных.

Я создал новый элемент управления, который наследуется от Combobox, и добавил новую команду с именем ‘addCommand’, а затем создал шаблон, который добавит новую кнопку в combobox, которая называется ‘Add’. Когда я привязываю команду кнопки к «addCommand» через TemplateBinding, это не сработает.

Я создал пользовательский элемент управления следующим образом:

     public class ZeroOneCombobox : ComboBox
    {
        public ICommand AddCommand
        {
            get
            {
                return (ICommand)GetValue(AddCommandProperty);
            }

            set
            {
                SetValue(AddCommandProperty, value);
            }
        }

        public static readonly DependencyProperty AddCommandProperty =
            DependencyProperty.Register("AddCommand", typeof(ICommand), typeof(ZeroOneCombobox));
    }

  

Затем я создал шаблон управления следующим образом:

 
        <ControlTemplate x:Key="ZeroOneComboBoxControl" TargetType="{x:Type zoc:ZeroOneCombobox}"
                         xmlns:Themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero2">
            <Grid x:Name="templateRoot" SnapsToDevicePixels="True">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="20"/>
                    <ColumnDefinition Width="20"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition MinWidth="{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}" Width="0"/>
                </Grid.ColumnDefinitions>
                <Popup Grid.Column="2" x:Name="PART_Popup" AllowsTransparency="True" Grid.ColumnSpan="2" IsOpen="{Binding IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}" Margin="1" PopupAnimation="{DynamicResource {x:Static SystemParameters.ComboBoxPopupAnimationKey}}" Placement="Bottom">
                    <Themes:SystemDropShadowChrome x:Name="shadow" Color="Transparent" MaxHeight="{TemplateBinding MaxDropDownHeight}" MinWidth="{Binding ActualWidth, ElementName=templateRoot}">
                        <Grid>
                            <Border x:Name="DropDownBorder" BorderBrush="{DynamicResource {x:Static SystemColors.WindowFrameBrushKey}}" BorderThickness="1" Background="{DynamicResource {x:Static SystemColors.WindowBrushKey}}">
                                <ScrollViewer x:Name="DropDownScrollViewer">
                                    <VirtualizingStackPanel Name="ItemPanel" IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Contained" />
                                </ScrollViewer>
                            </Border>
                        </Grid>
                    </Themes:SystemDropShadowChrome>
                </Popup>

                <Button x:Name="Add" Grid.Column="0" Content=" " Style="{StaticResource ComboboxButton}" Command="{TemplateBinding AddCommand}" />

                <ToggleButton x:Name="toggleButton" 
                              BorderBrush="{TemplateBinding BorderBrush}" 
                              BorderThickness="{TemplateBinding BorderThickness}" 
                              Background="{TemplateBinding Background}" 
                              Grid.ColumnSpan="2" 
                              Grid.Column="2"
                              IsChecked="{Binding IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}">
                    <ToggleButton.Style>
                        <Style TargetType="{x:Type ToggleButton}">
                            <Setter Property="OverridesDefaultStyle" Value="True"/>
                            <Setter Property="IsTabStop" Value="False"/>
                            <Setter Property="Focusable" Value="False"/>
                            <Setter Property="ClickMode" Value="Press"/>
                            <Setter Property="Template">
                                <Setter.Value>
                                    <ControlTemplate TargetType="{x:Type ToggleButton}">
                                        <Border x:Name="templateRoot" BorderBrush="#FFACACAC" BorderThickness="{TemplateBinding BorderThickness}" SnapsToDevicePixels="True">
                                            <Border.Background>
                                                <LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
                                                    <GradientStop Color="#FFF0F0F0" Offset="0"/>
                                                    <GradientStop Color="#FFE5E5E5" Offset="1"/>
                                                </LinearGradientBrush>
                                            </Border.Background>
                                            <Border x:Name="splitBorder" BorderBrush="Transparent" BorderThickness="1" HorizontalAlignment="Right" Margin="0" SnapsToDevicePixels="True" Width="{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}">
                                                <Path x:Name="Arrow" Data="F1M0,0L2.667,2.66665 5.3334,0 5.3334,-1.78168 2.6667,0.88501 0,-1.78168 0,0z" Fill="#FF606060" HorizontalAlignment="Center" Margin="0" VerticalAlignment="Center"/>
                                            </Border>
                                        </Border>
                                        <ControlTemplate.Triggers>
                                            <MultiDataTrigger>
                                                <MultiDataTrigger.Conditions>
                                                    <Condition Binding="{Binding IsEditable, RelativeSource={RelativeSource FindAncestor, AncestorLevel=1, AncestorType={x:Type ComboBox}}}" Value="true"/>
                                                    <Condition Binding="{Binding IsMouseOver, RelativeSource={RelativeSource Self}}" Value="false"/>
                                                    <Condition Binding="{Binding IsPressed, RelativeSource={RelativeSource Self}}" Value="false"/>
                                                    <Condition Binding="{Binding IsEnabled, RelativeSource={RelativeSource Self}}" Value="true"/>
                                                </MultiDataTrigger.Conditions>
                                                <Setter Property="Background" TargetName="templateRoot" Value="White"/>
                                                <Setter Property="BorderBrush" TargetName="templateRoot" Value="#FFABADB3"/>
                                                <Setter Property="Background" TargetName="splitBorder" Value="Transparent"/>
                                                <Setter Property="BorderBrush" TargetName="splitBorder" Value="Transparent"/>
                                            </MultiDataTrigger>
                                            <Trigger Property="IsMouseOver" Value="True">
                                                <Setter Property="Fill" TargetName="Arrow" Value="Black"/>
                                            </Trigger>
                                            <MultiDataTrigger>
                                                <MultiDataTrigger.Conditions>
                                                    <Condition Binding="{Binding IsEditable, RelativeSource={RelativeSource FindAncestor, AncestorLevel=1, AncestorType={x:Type ComboBox}}}" Value="false"/>
                                                </MultiDataTrigger.Conditions>
                                                <Setter Property="Background" TargetName="templateRoot" Value="White"/>
                                            </MultiDataTrigger>
                                            <MultiDataTrigger>
                                                <MultiDataTrigger.Conditions>
                                                    <Condition Binding="{Binding IsMouseOver, RelativeSource={RelativeSource Self}}" Value="true"/>
                                                    <Condition Binding="{Binding IsEditable, RelativeSource={RelativeSource FindAncestor, AncestorLevel=1, AncestorType={x:Type ComboBox}}}" Value="true"/>
                                                </MultiDataTrigger.Conditions>
                                                <Setter Property="Background" TargetName="templateRoot" Value="White"/>
                                                <Setter Property="BorderBrush" TargetName="templateRoot" Value="#FF7EB4EA"/>
                                                <Setter Property="Background" TargetName="splitBorder">
                                                    <Setter.Value>
                                                        <LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
                                                            <GradientStop Color="#FFEBF4FC" Offset="0"/>
                                                            <GradientStop Color="#FFDCECFC" Offset="1"/>
                                                        </LinearGradientBrush>
                                                    </Setter.Value>
                                                </Setter>
                                                <Setter Property="BorderBrush" TargetName="splitBorder" Value="#FF7EB4EA"/>
                                            </MultiDataTrigger>
                                            <Trigger Property="IsPressed" Value="True">
                                                <Setter Property="Fill" TargetName="Arrow" Value="Black"/>
                                            </Trigger>
                                            <MultiDataTrigger>
                                                <MultiDataTrigger.Conditions>
                                                    <Condition Binding="{Binding IsPressed, RelativeSource={RelativeSource Self}}" Value="true"/>
                                                    <Condition Binding="{Binding IsEditable, RelativeSource={RelativeSource FindAncestor, AncestorLevel=1, AncestorType={x:Type ComboBox}}}" Value="false"/>
                                                </MultiDataTrigger.Conditions>
                                                <Setter Property="Background" TargetName="templateRoot">
                                                    <Setter.Value>
                                                        <LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
                                                            <GradientStop Color="#FFDAECFC" Offset="0"/>
                                                            <GradientStop Color="#FFC4E0FC" Offset="1"/>
                                                        </LinearGradientBrush>
                                                    </Setter.Value>
                                                </Setter>
                                                <Setter Property="BorderBrush" TargetName="templateRoot" Value="#FF569DE5"/>
                                            </MultiDataTrigger>
                                            <MultiDataTrigger>
                                                <MultiDataTrigger.Conditions>
                                                    <Condition Binding="{Binding IsPressed, RelativeSource={RelativeSource Self}}" Value="true"/>
                                                    <Condition Binding="{Binding IsEditable, RelativeSource={RelativeSource FindAncestor, AncestorLevel=1, AncestorType={x:Type ComboBox}}}" Value="true"/>
                                                </MultiDataTrigger.Conditions>
                                                <Setter Property="Background" TargetName="templateRoot" Value="White"/>
                                                <Setter Property="BorderBrush" TargetName="templateRoot" Value="#FF569DE5"/>
                                                <Setter Property="Background" TargetName="splitBorder">
                                                    <Setter.Value>
                                                        <LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
                                                            <GradientStop Color="#FFDAEBFC" Offset="0"/>
                                                            <GradientStop Color="#FFC4E0FC" Offset="1"/>
                                                        </LinearGradientBrush>
                                                    </Setter.Value>
                                                </Setter>
                                                <Setter Property="BorderBrush" TargetName="splitBorder" Value="#FF569DE5"/>
                                            </MultiDataTrigger>
                                            <Trigger Property="IsEnabled" Value="False">
                                                <Setter Property="Fill" TargetName="Arrow" Value="#FFBFBFBF"/>
                                            </Trigger>
                                            <MultiDataTrigger>
                                                <MultiDataTrigger.Conditions>
                                                    <Condition Binding="{Binding IsEnabled, RelativeSource={RelativeSource Self}}" Value="false"/>
                                                    <Condition Binding="{Binding IsEditable, RelativeSource={RelativeSource FindAncestor, AncestorLevel=1, AncestorType={x:Type ComboBox}}}" Value="false"/>
                                                </MultiDataTrigger.Conditions>
                                                <Setter Property="Background" TargetName="templateRoot" Value="#FFF0F0F0"/>
                                                <Setter Property="BorderBrush" TargetName="templateRoot" Value="#FFD9D9D9"/>
                                            </MultiDataTrigger>
                                            <MultiDataTrigger>
                                                <MultiDataTrigger.Conditions>
                                                    <Condition Binding="{Binding IsEnabled, RelativeSource={RelativeSource Self}}" Value="false"/>
                                                    <Condition Binding="{Binding IsEditable, RelativeSource={RelativeSource FindAncestor, AncestorLevel=1, AncestorType={x:Type ComboBox}}}" Value="true"/>
                                                </MultiDataTrigger.Conditions>
                                                <Setter Property="Background" TargetName="templateRoot" Value="White"/>
                                                <Setter Property="BorderBrush" TargetName="templateRoot" Value="#FFBFBFBF"/>
                                                <Setter Property="Background" TargetName="splitBorder" Value="Transparent"/>
                                                <Setter Property="BorderBrush" TargetName="splitBorder" Value="Transparent"/>
                                            </MultiDataTrigger>
                                        </ControlTemplate.Triggers>
                                    </ControlTemplate>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </ToggleButton.Style>
                </ToggleButton>
                <TextBox x:Name="contentPresenter" Grid.Column="2"
                                                   Text="{TemplateBinding Text}" 
                                                   HorizontalAlignment="Stretch" 
                                                   IsHitTestVisible="False" Margin="{TemplateBinding Padding}" 
                                                   SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" 
                                                   VerticalAlignment="Stretch"
                                                   BorderThickness="0"
                                                   IsEnabled="True" 
                                                   IsReadOnly="False"
                                                   IsTabStop="False" />
            </Grid>
            <ControlTemplate.Triggers>
                <Trigger Property="HasDropShadow" SourceName="PART_Popup" Value="True">
                    <Setter Property="Margin" TargetName="shadow" Value="0,0,5,5"/>
                    <Setter Property="Color" TargetName="shadow" Value="#71000000"/>
                </Trigger>
                <Trigger Property="HasItems" Value="False">
                    <Setter Property="Height" TargetName="DropDownBorder" Value="95"/>
                </Trigger>
                <MultiTrigger>
                    <MultiTrigger.Conditions>
                        <Condition Property="IsGrouping" Value="True"/>
                        <Condition Property="VirtualizingPanel.IsVirtualizingWhenGrouping" Value="False"/>
                    </MultiTrigger.Conditions>
                    <Setter Property="ScrollViewer.CanContentScroll" Value="False"/>
                </MultiTrigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>

  

Когда я привязываю команду к ViewModel, например, следуйте:

  <zoc:ZeroOneCombobox  x:Name="Comb" DisplayMemberPath="Name" Template="{StaticResource AdvComboBoxControl}"
                              AddCommand="{Binding ViewAccountCommand}" Margin="163,234,308.6,154" />
  

Команда не запускается, когда я нажимаю на кнопку добавления…

Пожалуйста, помогите!

Комментарии:

1. Вы не задаете никакой команде значение AddCommand , поэтому она не выполняется.

2. Исправьте последний код, я установил ‘addCommand’, но все еще не работает…

3. Это должно сработать, возможно, ваша привязка не работает, потому что контекст данных неверен. Проверьте окно вывода на наличие привязки или других ошибок.

4. на выходе не было никаких ошибок

5. на выходе не было никаких ошибок