wpf customControl 绑定 itemscontrol DataTemplate 按钮

wpf customControl binding itemscontrol DataTemplate button

我是 WPF 的新手,所以我在自定义控件单击按钮上遇到了一些绑定问题。

我有一个带有水印和 selctedItems 属性的文本框。控制 selecteditems != null 在控件中显示它们,如下所示:

link转图片 [http://s29.postimg.org/p25qgqzwn/image.jpg][1]

现在我需要连接 X 按钮以从 selectedItems 源中删除该项目。 我正在尝试在 OnApplyTemplate 方法中执行此操作,但我不知道如何访问 itemscontrol 中的那个按钮以附加鼠标单击事件。

我的Xaml

<Style TargetType="{x:Type local:TextBoxPicker}">
    <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.WindowBrushKey}}"/>
    <Setter Property="BorderBrush" Value="{StaticResource TextBox.Static.Border}"/>
    <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
    <Setter Property="BorderThickness" Value="1"/>
    <Setter Property="KeyboardNavigation.TabNavigation" Value="None"/>
    <Setter Property="HorizontalContentAlignment" Value="Left"/>
    <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
    <Setter Property="AllowDrop" Value="true"/>
    <Setter Property="ScrollViewer.PanningMode" Value="VerticalFirst"/>
    <Setter Property="Stylus.IsFlicksEnabled" Value="False"/>
    <Setter Property="WatermarkTemplate" Value="{StaticResource DefaultWatermarkTemplate}"/>
    <Setter Property="SelectedItemsTemplate" Value="{StaticResource DefaultSelectedItemsTemplate}" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:TextBoxPicker}">
                <Grid>
                    <Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
                        <ScrollViewer x:Name="PART_ContentHost" Focusable="false" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"/>
                    </Border>
                    <Border BorderBrush="Red" BorderThickness="1">
                        <ContentControl x:Name="PART_WatermarkHost"
                                Content="{TemplateBinding Watermark}"
                                ContentTemplate="{TemplateBinding WatermarkTemplate}"
                                VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                                HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                IsHitTestVisible="False"
                                Margin="{TemplateBinding Padding}"
                                Visibility="Collapsed" />
                    </Border>

                    <Border BorderBrush="Green" BorderThickness="1">
                        <ItemsControl x:Name="PART_SelectedItemsHost"
                                ItemsSource="{TemplateBinding SelectedItems}"
                                ItemTemplate="{TemplateBinding SelectedItemsTemplate}"
                                VerticalAlignment="Stretch"
                                HorizontalAlignment="Stretch"                                                                      
                                Margin="{TemplateBinding Padding}"
                                Visibility="Visible">
                            <ItemsControl.ItemsPanel>
                                <ItemsPanelTemplate>
                                    <WrapPanel>
                                    </WrapPanel>
                                </ItemsPanelTemplate>
                            </ItemsControl.ItemsPanel>
                        </ItemsControl>

                    </Border>
                </Grid>
               ....
            </ControlTemplate>
        </Setter.Value>
    </Setter>

我的 ItemTemplate 看起来像这样

xaml:

<DataTemplate x:Key="DefaultSelectedItemsTemplate" >
    <Border x:Name="selectedItemBorder" BorderBrush="Gray" BorderThickness="1" CornerRadius="5" Background="{DynamicResource {x:Static SystemColors.ControlBrushKey}}" Margin="5,1,1,1">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="15"/>
            </Grid.ColumnDefinitions>
            <!--<TextBlock Grid.Column="0" Text="{Binding RelativeSource={RelativeSource Self}, Path=Ime}" Margin="5,0,3,0"></TextBlock>-->
            <TextBlock Grid.Column="0" Text="{Binding}" Margin="5,0,3,0"></TextBlock>
            <Button x:Name="PART_selectedItemButton" BorderThickness="0" Grid.Column="1" >X</Button>
        </Grid>
    </Border>
</DataTemplate>

.cs代码

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        ItemsControl selectedItem = GetTemplateChild("PART_SelectedItemsHost") as ItemsControl;

        if (selectedItem != null)
        {
            selectedItem.MouseLeftButtonDown += new MouseButtonEventHandler(selectedItemBorder_MouseLeftButtonDown);

            // blind click on X buttons in ItemsControl
        }

    }

那么我如何绑定单击代码隐藏项目上的 "X" 按钮?

首先是带有 ObservableCollection 的视图模型和将执行 X 的命令:

private ObservableCollection<string> items = new ObservableCollection<string>() { "One", "Two", "Three" };
    public ObservableCollection<String> Items
    {
        get
        {
            return items;
        }
        set
        {
            items = value;
            NotifyPropertyChanged();
        }
    }

    public Command<String> DeleteItem
    {
        get
        {
            return new Command<string>((item) =>
            {
                if (items.Contains(item))
                {
                    items.Remove(item);
                }
                NotifyPropertyChanged("Items");
            });
        }
    }

现在 XAML:

资源,它绑定到 'parent' 数据上下文,这是了解绑定去向的简单方法:

<Page.Resources>
    <DataTemplate x:Key="DefaultSelectedItemsTemplate" >
        <Border x:Name="selectedItemBorder" BorderBrush="Gray" BorderThickness="1" CornerRadius="5"  Margin="5,1,1,1">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="15"/>
                </Grid.ColumnDefinitions>
                <!--<TextBlock Grid.Column="0" Text="{Binding RelativeSource={RelativeSource Self}, Path=Ime}" Margin="5,0,3,0"></TextBlock>-->
                <TextBlock Grid.Column="0" Text="{Binding}" Margin="5,0,3,0"></TextBlock>
                <Button x:Name="PART_selectedItemButton" BorderThickness="0" Grid.Column="1" Command="{Binding DataContext.DeleteItem, ElementName=ItemsControlInstance}" CommandParameter="{Binding}">X</Button>
            </Grid>
        </Border>
    </DataTemplate>
</Page.Resources>

最后是项目控件:

<ItemsControl x:Name="ItemsControlInstance" ItemTemplate="{StaticResource DefaultSelectedItemsTemplate}" ItemsSource="{Binding Items}"/>

最后我设法使它工作,在 Jaun 的帮助和指导下它仍然没有工作(我尝试了大概 10 种不同的东西并且它在 DataContext 中..它从未被绑定。

所以在我的重写 OnApplyTemplate 上我添加了 this.DataContext = 这个 ... 所以我错过了那部分。

我使用 AttachedCommandBehavior (nuget) 命令

代码:

public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        this.DataContext = this;

        ItemsControl itmControl = GetTemplateChild("PART_SelectedItemsHost") as ItemsControl;

        if (itmControl != null)
        {
            itmControl.MouseLeftButtonDown += new MouseButtonEventHandler(itmControl_MouseLeftButtonDown);

            // blind click on X buttons in ItemsControl
        }

    }