0

好的,我正在阅读这篇文章,它展示了如何在当前 XAML 中将自定义添加TabItem到 aTabControl中,但是如果我想在 XAML中添加TabItems到自定义中呢?TabControl

所以我创建了我的自定义TabControl UserControl

<UserControl x:Class="myLibrary.MyTabControl">
    <DockPanel LastChildFill="True">
        <Grid DockPanel.Dock="Bottom"/>>
    </DockPanel>
    <TabControl x:Name=tc">
        <TabControl.LayoutTransform>
            <!-- Allows to zoom the control's content using the slider -->
            <ScaleTransform CenterX="0" 
                CenterY="0"
                ScaleX="{Binding ElementName=uiScaleSlider,Path=Value}"
                ScaleY="{Binding ElementName=uiScaleSlider,Path=Value}"/>
        </TabControl.LayoutTransform>
    </TabControl>
</UserControl>

然后,我想将静态添加TabItems到 中MyUserControl UserControl,如下所示

<UserControl x:Class="MyLibrary.Forms.MyTabForm"
    xmlns:Utilities="clr-namespace:myLibrary;assembly=myLibrary">
<Utilities:MyTabControl DockPanel.Dock="Top">
    <tc>
        <tc.Items>
            <TabItem Header="Tab 0"/>
            <TabItem Header="Tab 1"/>
        </tc.Items>
    </tc>
</Utilities:MyTabControl>
</UserControl>

而不是使用默认的 WPF TabControl

<TabControl Name="tabControl1" Margin="0, 10, 0, 0"  DockPanel.Dock="Top">
    <TabItem Header="Tab 0 (0)" Name="tabItem0">
        <Grid Name="tabItem0Grid" />
    </TabItem>
    <TabItem Header="Tab 1 (0)" Name="tabItem1">
        <Grid Name="tabItem1Grid" />
    </TabItem>

4

2 回答 2

0

您需要添加一个DependencyProperty,以UserControl使用户能够Bind将项目添加到TabControl.Items控件中的属性中:

public static readonly DependencyProperty ItemsProperty = DependencyProperty.
    Register("Items", typeof(ItemCollection), typeof(MyTabControl));

public ItemCollection Items
{
    get { return (ItemCollection)GetValue(ItemsProperty); }
    set { SetValue(ItemsProperty, value); }
} 

然后你可以Bind在你的控件中使用RelativeSource Binding这样的这个属性:

<UserControl x:Class="myLibrary.MyTabControl">
    <DockPanel LastChildFill="True">
        <Grid DockPanel.Dock="Bottom"/>>
    </DockPanel>
    <TabControl x:Name=tc" Items="{Binding RelativeSource={RelativeSource 
        AncestorType={x:Type YourXmlNamespace:MyTabControl}}}">
        <TabControl.LayoutTransform>
            <!-- Allows to zoom the control's content using the slider -->
            <ScaleTransform CenterX="0" 
                CenterY="0"
                ScaleX="{Binding ElementName=uiScaleSlider,Path=Value}"
                ScaleY="{Binding ElementName=uiScaleSlider,Path=Value}"/>
        </TabControl.LayoutTransform>
    </TabControl>
</UserControl>

然后你可以像这样使用它:

<Utilities:MyTabControl DockPanel.Dock="Top" Items="{Binding SomeItemCollection}" />
于 2013-11-11T15:57:35.657 回答
0
  1. 将 IEnumerable 的依赖属性类型添加到您的User ControlUserControlItemsSource例如)
  2. 将选项卡控件的属性绑定ItemsSource到此依赖项属性 ( ItemsSource="{Binding UserControlItemsSource,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type UserControl}}}")
  3. 当您使用您的用户控件时 - 绑定您的用户控件 ( UserControlItemsSource) 的依赖属性。
于 2016-06-05T09:38:38.773 回答