考虑以下用户控件:
这是我编写的具有两个嵌套元素的自定义用户控件。
FilterContent显示一种特殊类型的标记,用于过滤屏幕右侧的内容
MainContent托管过滤后的内容。
控件的唯一真正目的是在整个应用程序中提供一致的 UI 和动画,因为这种过滤器/内容模式经常使用。
用户控件的(简化的)Xaml 如下所示:
<UserControl>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="3*"/>
<ColumnDefinition Width="7*"/>
</Grid.ColumnDefinitions>
<ContentPresenter Grid.Column="0" Content="{Binding ElementName=filterControl, Path=FilterControl}" DataContext="{Binding}" />
<ContentPresenter Grid.Column="1" Content="{Binding ElementName=filterControl, Path=MainControl}" DataContext="{Binding}" />
</Grid>
代码隐藏是:
public sealed partial class FilterPaneControl : UserControl
{
public static DependencyProperty FilterControlProperty = DependencyProperty.Register("FilterControl", typeof(object), typeof(FilterPaneControl), new PropertyMetadata(default(object), PropertyChangedCallback));
public static DependencyProperty MainControlProperty = DependencyProperty.Register("MainControl", typeof (object), typeof (FilterPaneControl), new PropertyMetadata(default(object)));
public FilterPaneControl()
{
this.InitializeComponent();
}
public object FilterControl
{
get { return (object)GetValue(FilterControlProperty); }
set { SetValue(FilterControlProperty, value); }
}
public object MainControl
{
get { return (object) GetValue(MainControlProperty); }
set { SetValue(MainControlProperty, value); }
}
}
在实现页面中控件的用法是:
<Generic:FilterPaneControl>
<Generic:FilterPaneControl.FilterControl>
<Grid>
<TextBlock Text="Filter Content here"/>
</Grid>
</Generic:FilterPaneControl.FilterControl>
<Generic:FilterPaneControl.MainControl>
<Grid>
<TextBlock Text="Main Content here"/>
</Grid>
</Generic:FilterPaneControl.MainControl>
</Generic:FilterPaneControl>
这很好用!
问题
问题是当我想从实现页面引用控件中的一些内容时。一个很好的例子是处理快照/纵向的视觉状态(WinRT 实现)
<Generic:FilterPaneControl>
<Generic:FilterPaneControl.FilterControl>
<Grid>
<TextBlock x:Name="filterContent1" Text="Filter Content here"/>
</Grid>
</Generic:FilterPaneControl.FilterControl>
<Generic:FilterPaneControl.MainControl>
<Grid>
<TextBlock Text="Main Content here"/>
</Grid>
</Generic:FilterPaneControl.MainControl>
</Generic:FilterPaneControl>
<VisualStateManager.VisualStateGroups>
<VisualState x:Name="FullScreenPortrait">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="filterContent1" Storyboard.TargetProperty="Width">
<DiscreteObjectKeyFrame KeyTime="0" Value="200"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateManager.VisualStateGroups>
这会导致运行时异常,因为 visualstatemanager 无法找到引用的元素“filterContent1”,即使它存在于可视树中。此外,如果我尝试直接在 Page.Loaded 事件处理程序中引用该元素,则 filterContent1 为空。
好像嵌套的 Xaml 直到稍后才会呈现 - 这也抛出了 visualstatemanager。
有什么建议么?