0

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

<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,它包含一个按钮。当该按钮单击项目控件中的项目时,我希望在父控件中处理该命令。

4

1 回答 1

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>
于 2013-05-03T06:25:48.227 回答