已更改两个依赖项 属性 而不是一个

Two dependency property have been changed instead of one

我正在创建基于边框和标签的用户控件。我想将 UserControl 的 Content 属性 设置为 Label 的 Content 属性.

有一个UserControl的WPF代码:

<UserControl x:Class="TestApp.TabButton"
         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:local="clr-namespace:TestApp"
         mc:Ignorable="d" 
         d:DesignHeight="450" d:DesignWidth="800">
<Border x:Name="TabButtonBorder">
    <Label x:Name="TabButtonLabel" Foreground="White" HorizontalAlignment="Left" VerticalAlignment="Center" Content="test content"/>
</Border>

还有一个class代码:

    public partial class TabButton : UserControl
{

    public TabButton()
    {
        InitializeComponent();
        TabButtonLabel.DataContext = this;

        DependencyPropertyDescriptor contentDescriptor = DependencyPropertyDescriptor.FromProperty(ContentProperty, typeof(TabButton));
        contentDescriptor.AddValueChanged(TabButtonLabel, (s, e) => { ((Label)s).Content = Content; });
    }
}

它按我想要的方式工作,但在内容更新后,标签的前景变为黑色,但正如您在代码中看到的那样,它应该是白色的。为什么会这样?

不确定你到底想达到什么目的,但是一个总是在 Border 中使用 Label 来可视化它的 Content 的用户控件应该通过它的 ControlTemplate。不需要额外的代码。

<UserControl x:Class="TestApp.TabButton"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <UserControl.Template>
        <ControlTemplate TargetType="UserControl">
            <Border>
                <Label Foreground="White" Content="{TemplateBinding Content}"/>
            </Border>
        </ControlTemplate>
    </UserControl.Template>
</UserControl>