如果源代码是主UI,XAML绑定不起作用?

ql3eal8s  于 2023-08-01  发布在  其他
关注(0)|答案(1)|浏览(119)

这是我的代码

自定义类

public class CustomClass : Control
{
    public TabControl TabControl1
    {
        get { return (TabControl)GetValue(TabControl1Property); }
        set { SetValue(TabControl1Property, value); }
    }

    public static readonly DependencyProperty TabControl1Property =
        DependencyProperty.Register("TabControl1", typeof(TabControl), typeof(CustomClass), new PropertyMetadata(null));

}

字符串

MainWindow.xaml

<Window x:Class="SampleWithoutSFControl.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:SampleWithoutSFControl"
        mc:Ignorable="d"
 
        Title="MainWindow" Height="450" Width="800">

    <local:CustomClass >
        <local:CustomClass.TabControl1>
            <TabControl>
                <TabItem x:Name="tabItem" Header="Item1" DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:MainWindow}}}">
                    <Label Content="{Binding Name1}"/>
                </TabItem>
            </TabControl>
        </local:CustomClass.TabControl1>
    </local:CustomClass>
</Window>

MainWindow.xaml.cs

public partial class MainWindow : Window
    {
        
        public MainWindow()
        {
            InitializeComponent();
           // tabItem.DataContext = this;  //but uncomment this solves the problem!
        }
        public string Name1 => "Sync";
    }


运行代码,尝试打开“TabControl可见性”复选框。请注意,“Sync”不会出现在TabItem中,尽管它应该出现,因为TabItem的DataContext被设置为MainWindow控件。
为了解决这个问题,我需要通过取消注解这行代码来设置DataContext

// tabItem.DataContext = this;


但这两者不是完全等同的吗?为什么会这样?

niknxzdl

niknxzdl1#

您应该使用ControlTemplate来呈现您设置了TabControl1属性的TabControl

<local:CustomClass>
    <local:CustomClass.TabControl1>
        <TabControl>
            <TabItem x:Name="tabItem" Header="Item1" DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:MainWindow}}}">
                <Label Content="{Binding Name1}"/>
            </TabItem>
        </TabControl>
    </local:CustomClass.TabControl1>
    <local:CustomClass.Template>
        <ControlTemplate TargetType="local:CustomClass">
            <ContentControl Content="{TemplateBinding TabControl1}" />
        </ControlTemplate>
    </local:CustomClass.Template>
</local:CustomClass>

字符串
如果不这样做,您将根本看不到包含数据绑定LabelTabControl
请注意,如果您希望重用该控件,您显然应该为其定义默认样式/模板。

相关问题