[英]Silverlight 4: Binding ChildControl to ParentControl
在TabItem样式中,我有一个按钮。 该按钮具有一个命令,我想将其发送给(父项)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)作为子控件的命令参数传递?
高度赞赏。
您可以在Binding中使用RelativeSource Mode Self
或TemplatedParent
,然后在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;
}
您可以使用{RelativeSource Self},然后在命令处理程序代码中使用Parent属性向上查找所需的控件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.