【问题标题】:ElementName not working when assigning DataTemplate from code behind?从后面的代码分配 DataTemplate 时 ElementName 不起作用?
【发布时间】:2011-03-13 20:33:48
【问题描述】:

我正在尝试使用 DataTemplate 中的 ElementName 访问控件,该控件用于与定义(在 xaml 中)不同的 UserControl(资源)中。

想象一下这种情况:

MyUserControl.xaml 在资源中具有以下 DataTemplate:

<UserControl.Resources>
   <DataTemplate x:Key="SomeTemplate">
      <TextBlock Text="{Binding Text, ElementName=TextElement}"/>
   </DataTemplate>
</UserControl.Resources>
<Grid x:Name="LayoutRoot">
    <TextBlock x:Name="TextElement" Text="IT WORKS! (not...)"/>
</Grid>
</UserControl>

MyUserControlWrapper.xaml

<ContentPresenter x:Name="ContentPresenter" Content="{Binding SomeContent}"/>

在 MyUserControlWrapper.xaml 后面的代码中,我从 MyUserControl.xaml 设置 ContentPresenter 的 ContentTemplate:

类似:

ContentPresenter.ContentTemplate = (DataTemplate)childView.Resources["SomeTemplate"];

是否可以从在 UserControl 外部定义的资源中使用 ElementName?

DataTemplate 如何在同一个 UserControl 中搜索 ElementName?也许可以为 DataTemplate 本身设置 DataContext 之类的东西,以便 ElementName 工作,而不会弄乱发送到 Template 内部使用的控件的 DataContext?

【问题讨论】:

  • 为了帮助您找到解决方案,最好展示“MyUserContolWrapper”的放置方式。目前还不清楚它与 MyUserControl 的关系。
  • 我在后面的代码中构建初始视图并将其放置在 Wrapper 的 ContentPresenter 中。 Wrapper 类型的“增强”基本视图,带有一些功能,如工具栏、侧边栏等。所以包装的视图可能看起来像 [ Toolbar ] [Side][ Original view ] [ InfoFrame ] 在原始视图中,您可以使用控制包装内容的某些部分模板。这是通过定义严格名称的 DataTemplates 来完成的。想象一下,包装器定义了 InfoFrame 的设计(边框、位置等),但 InfoFrame 中的信息本身是从原始视图的 DataTemplate x:Key="InfoContent" 加载的。

标签: silverlight binding resources user-controls datatemplate


【解决方案1】:

也许你可以直接使用RelativeSource 和FindAncestor 走上VisualTree? 这里有一个很好的展示不同的绑定变体: http://www.wpfwiki.com/Default.aspx?Page=WPF%20Q5.3&AspxAutoDetectCookieSupport=1

【讨论】:

    【解决方案2】:

    你需要复习与Namescopes相关的概念。

    简要名称的范围是加载 Xaml 资源的位置。例如,每个 UserControl 都将加载自己的 Xaml,因此具有自己的名称范围。在您的情况下,您要求MyUserControlWrapper 查找其LoadComponent 未见过的名称。

    【讨论】:

    • 有没有办法从代码隐藏中将任何控件的 Namescope 分配/设置给 DataTemplate?
    猜你喜欢
    • 2011-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-25
    • 2012-03-15
    • 1970-01-01
    相关资源
    最近更新 更多