我正在尝试创建一个自定义TabItem,它动态添加到WPF窗口中定义的TabControl。我的自定义控件有一个对象,其中包含我想要绑定到模板特定部分的数据。
<Style TargetType="{x:Type local:EntityTabItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:EntityTabItem}">
<Border>
<Grid>
<Border x:Name="borderTop" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}"/>
<StackPanel Orientation="Horizontal" Margin="0,0,2,0">
<!-- Want to bind the FileName to this TextBlock -->
<TextBlock VerticalAlignment="Center" Text="{Binding Path=Entity.FileName}" Margin="-1,0,0,0" Padding="6,1,10,1"/>
<Button x:Name="closeButton" VerticalAlignment="Center" Content="X" Style="{StaticResource TabCloseButton}"/>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<Grid Background="White">
<!-- Want to bind the FileText to this TextBox -->
<TextBox Margin="15,0,0,0" BorderBrush="{x:Null}" Text="{Binding Path=Entity.FileText}"/>
</Grid>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
这是自定义控件CS文件:
public class EntityTabItem : TabItem
{
public Entity MyEntity { get; set; }
public EntityTabItem(string path)
{
this.MyEntity = new Entity(path);
}
static EntityTabItem()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(EntityTabItem), new FrameworkPropertyMetadata(typeof(EntityTabItem)));
}
}
我很确定我需要在某处设置DataBinding / Source,但我无法弄清楚在哪里绑定它以使我的TextBlock中的绑定起作用。
老实说,我根本无法绕过DataBinding。有一半的时间,我让它工作得很好而没有意识到如何,而另一半的时间它没有做任何事情。
我还尝试将“Entity”对象实现为DependencyProperty,但无法使其工作。因为我只在CS中创建我的自定义TabItem(从未直接在XAML中使用),这甚至是否重要?
答案 0 :(得分:0)
尝试使用DataContext属性,例如:
<Style TargetType="{x:Type local:EntityTabItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:EntityTabItem}">
<Border>
<Grid>
<Border x:Name="borderTop" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}"/>
<StackPanel Orientation="Horizontal" Margin="0,0,2,0">
<!-- Want to bind the FileName to this TextBlock -->
<TextBlock VerticalAlignment="Center" Text="{Binding Path=FileName}" Margin="-1,0,0,0" Padding="6,1,10,1"/>
<Button x:Name="closeButton" VerticalAlignment="Center" Content="X" Style="{StaticResource TabCloseButton}"/>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<Grid Background="White">
<!-- Want to bind the FileText to this TextBox -->
<TextBox Margin="15,0,0,0" BorderBrush="{x:Null}" Text="{Binding Path=FileText}"/>
</Grid>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
public class EntityTabItem : TabItem
{
private Entity _myEntity;
public Entity MyEntity
{
get { return _myEntity; }
set
{
_myEntity = value;
DataContext = value;
}
}
public EntityTabItem(string path)
{
this.MyEntity = new Entity(path);
}
static EntityTabItem()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(EntityTabItem), new FrameworkPropertyMetadata(typeof(EntityTabItem)));
}
}