【问题标题】:TabControl: first TabItem static, rest from code-behindTabControl:第一个 TabItem 静态,其余来自代码隐藏
【发布时间】:2015-08-19 02:05:55
【问题描述】:

我有一个UserControl,其中包含一个TabControl。
TabControl 将有 1 到 n TabItems,即:第一个 TabItem 将始终存在,并且它的内容对于我的 UserControl 的每个实例都是相同的,但其余的 TabItems 应该来自我的代码隐藏因为我必须先根据某些属性来构建它们。

我的第一次尝试包括

<UserControl x:Class="MyNS.MyControl"
             xmlns:local="MyNS"
             and the whole rest of the declarations>
  <Grid>
    <TabControl>
      <TabControl.ItemsSource>
        <Binding Path="Tabs" RelativeSource="{RelativeSource AncestorType=local:MyControl}" />
      </TabControl.ItemsSource>
    <TabControl/>
  </Grid>
</UserControl>

其中Tabs 在代码隐藏中声明为public IList Tabs { get { return ... } }。它不是依赖项或附加属性。这只是一个简单的字段。
这工作正常。无论我在代码隐藏中构造什么,都会显示出来。

但是,当我想手动定义第一个 TabItem 时,我遇到了问题:

<UserControl x:Class="MyNS.MyControl"
             xmlns:local="MyNS"
             and the whole rest of the declarations>
  <Grid>
    <TabControl>
      <TabControl.ItemsSource>
        <CompositeCollection>
          <CollectionContainer>
            <CollectionContainer.Collection>
              <x:Array Type="TabItem">
                <TabItem Header="Test"/>
              </x:Array>
            </CollectionContainer.Collection>
          </CollectionContainer>
          <CollectionContainer>                        
            <CollectionContainer.Collection>
              <Binding Path="Tabs"
                       RelativeSource="{RelativeSource AncestorType={x:Type local:MyControl}}"/>
            </CollectionContainer.Collection>                        
          </CollectionContainer>              
        </CompositeCollection>
      </TabControl.ItemsSource>
    <TabControl/>
  </Grid>
</UserControl>

始终显示第一个(静态)项目,但似乎绑定无法解析我的 Tabs 的 getter。

如何手动定义第一个选项卡项(在 XAML 中)并从代码隐藏中获取其余部分?

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

    使用{x:Reference}:

    <UserControl x:Class="MyNS.MyControl"
             xmlns:local="MyNS"
             x:Name="MyControl">
    
    <!-- ... --->
    
    <CollectionContainer Collection="{Binding Tabs, Source={x:Reference MyControl}}"/>
    

    【讨论】:

    • 我不得不将完整的CompositeCollection 移动到用户控件的资源中,但基本上这可以按预期工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-28
    • 2015-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多