Silverlight 4:将ChildControl绑定到ParentControl

时间:2011-01-29 17:41:01

标签: c# .net silverlight xaml controltemplate

在TabItem样式中我有一个Button。那个Button有一个命令,我想将(Parent)TabItem发送给。在Silverlight中,我们没有RelativeSource。但我不能简单地使用Elementname。因为我的TabItem在样式中没有名称。

<Style TargetType="sdk:TabItem">
                        <Setter Property="HeaderTemplate">
                            <Setter.Value>
                                <DataTemplate>                                  
                                    <StackPanel Orientation="Horizontal">                                        
                                        <TextBlock Text="{Binding TabCaption}"/>
                                        <Button Margin="8,0,0,0" 
                                                Command="local:Commands.CloseTabItem" 
                                                CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type sdk:TabItem}}}" 
                                                HorizontalContentAlignment="Center" 
                                                VerticalContentAlignment="Center">                                            
                                        </Button>
                                    </StackPanel>
                                </DataTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>

这将是Command方法中的代码:

private void OnCloseTabItemExecute(object sender, ExecutedRoutedEventArgs e)
{
    TabItem parent = e.Parameter as TabItem;

    if (parent != null)
    {
        FrameworkElement view = (parent as TabItem).Content as FrameworkElement;
        string regionName = RegionManager.GetRegionName(view);

        _regionManager.Regions[regionName].Remove(view);
    }
}

如何在Silverlight 4中传递父控件(TabItem)作为子控件的命令参数?

高度赞赏。

2 个答案:

答案 0 :(得分:1)

您可以在Binding中使用RelativeSource模式SelfTemplatedParent,然后在Command方法中向上查看可视树以查找TabItem

<强>的Xaml

<Button Margin="8,0,0,0"
        Command="local:Commands.CloseTabItem"
        CommandParameter="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}}"     
        HorizontalContentAlignment="Center"
        VerticalContentAlignment="Center">
</Button>

命令方法和GetVisualParent的实现

private void OnCloseTabItemExecute(object sender, ExecutedRoutedEventArgs e)
{
    DependencyObject element = e.Parameter as DependencyObject;
    TabItem tabItem = GetVisualParent<TabItem>(element);
    //...
}
public static T GetVisualParent<T>(object childObject) where T : FrameworkElement
{
    DependencyObject child = childObject as DependencyObject;
    while ((child != null) && !(child is T))
    {
        child = VisualTreeHelper.GetParent(child);
    }
    return child as T;
}

答案 1 :(得分:0)

您可以使用{RelativeSource Self}然后在命令处理程序代码中使用Parent属性向上查找所需的控件。