父控件中的Handle Button命令

时间:2013-05-02 13:38:25

标签: c# wpf

我有一个用户控件,其主要内容如下所示

<ItemsControl Grid.Row="0" ItemsSource="{Binding myCollection}" HorizontalContentAlignment="Stretch" x:Name="lstExpander" >
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal" IsItemsHost="True" FlowDirection="LeftToRight" Margin="0,0,0,0" />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemContainerStyle>
            <Style TargetType="ContentPresenter">
                <Setter Property="Margin" Value="100,0,0,0"></Setter>
            </Style>
        </ItemsControl.ItemContainerStyle>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <local:AttributeExpander>/local:AttributeExpander>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

此控件的项目再次是用户控件,即ConditionalAttributeExpander,其中包含一个按钮。当该按钮单击项目控件中的项目时,我希望在父控件中处理该命令。

1 个答案:

答案 0 :(得分:0)

在我的AttrubuteExpander用户控件中我已经定义了一个依赖属性,如下所示

 public ICommand DeleteCommand
    {
        get { return (ICommand)GetValue(DeleteCommandProperty); }
        set { SetValue(DeleteCommandProperty, value); }
    }

    // Using a DependencyProperty as the backing store for DeleteCommandCommand.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty DeleteCommandProperty =
        DependencyProperty.Register("DeleteCommand", typeof(ICommand), typeof(AttrubuteExpander ), new UIPropertyMetadata(null));

我已将DeleteCommand属性绑定到我的用户控件中的按钮,如下所示

 <Button Width="20" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=my:AttributeExpander}, Path=DeleteCommand, Mode=OneWay}"
                            > 
                    </Button>

现在在我的Collection的容器中,即我的ViewModel,我已经将ICommand类型的属性定义为如下,并将用户控件的Command属性和依赖属性绑定在一起,并且工作正常

public ICommand DeleteCommand 
    {
        get 
        {
            if (deleteCommand == null)
            {
                deleteCommand = new RelayCommand(x => Remove(null));
            }

            return deleteCommand;
        }           
    }  

,xaml如下

<DataTemplate>
                <local:AttributeExpander DeleteConditionCommand="{Binding ElementName=lstExpander, Path=DataContext.DeleteCommand}"></local:AttributeExpander>
            </DataTemplate>