WPF数据绑定不适用于样式tabitem中的边框或文本块

时间:2015-07-10 14:11:13

标签: c# wpf xaml data-binding

我正在尝试将边框的背景和文本绑定在文本块中以更改事件。这两个项目都存在于已为应用程序设置样式的选项卡标题内。

如果我硬编码颜色和文本一切正常,但当我尝试绑定背景颜色和文本时,它们不再出现。为了让数据绑定正常工作,我缺少什么?

XAML

<UserControl x:Class="Project.TabPanel"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:controls="clr-namespace:Project"
             DataContext="{Binding RelativeSource={RelativeSource Self}}"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="600">

    <TabControl Style="{StaticResource LeftTabControl}" Background="#FAFAFAFA" HorizontalAlignment="Stretch">
        <TabItem x:Name="ConnectionLabelTab" Style="{StaticResource Tab2}" Focusable="False">
            <TabItem.HeaderTemplate>
                <DataTemplate>
                    <Border x:Name="ConnectionLabelBorder" Background="{Binding LabelColor}" Width="70">
                        <TextBlock x:Name="ConnectionLabelText"
                            Text="{Binding LabelText}" Padding="0,4,0,4"
                            Foreground="Black" HorizontalAlignment="Center" VerticalAlignment="Center" 
                            FontSize="10"/>
                    </Border>
                </DataTemplate>
            </TabItem.HeaderTemplate>
        </TabItem>
    </TabConrol>
</UserControl>

xaml.cs

/// <summary>
/// Interaction logic for TabPanel.xaml
/// </summary>
public partial class TabPanel : UserControl
{
    String green = "#FF0A7E07";
    BrushConverter bc = new BrushConverter();

    Brush labelcolor;
    String labeltext;

    public TabPanel()
    {
        labelcolor = (Brush)bc.ConvertFromString(green);
        labeltext = "Connected";

        InitializeComponent();   
    }

    public Brush LabelColor { get { return labelcolor; } }
    public String LabelText { get { return labeltext; } }
}

1 个答案:

答案 0 :(得分:1)

您在DataTemplate中有错误的DataContext,只需添加:

DataContext="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=DataContext}" 

到DataTemplate中的BorderControl,完成模板:

<DataTemplate>
    <Border x:Name="ConnectionLabelBorder" DataContext="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=DataContext}" Background="{Binding LabelColor}" Width="70">
        <TextBlock x:Name="ConnectionLabelText"
                   Text="{Binding LabelText}" Padding="0,4,0,4"
                   Foreground="Black" HorizontalAlignment="Center" VerticalAlignment="Center"
                   FontSize="10" />
    </Border>
</DataTemplate>