【问题标题】:Two dependency property have been changed instead of one改变了两个依赖属性而不是一个
【发布时间】:2021-07-06 00:22:33
【问题描述】:

我正在创建基于边框和标签的用户控件。我想将 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>

还有一个类代码:

    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; });
    }
}

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

【问题讨论】:

  • 这看起来很奇怪。为什么在 ControlTemplate 中没有通常的 ContentPresenter?为什么这是一个 UserControl,而不是例如派生标签?
  • 因为我还必须使用 Border 来设置控件的样式。通常我想在资源字典中为这个控件创建样式。
  • 这当然可以通过使用样式和模板的标准方式来实现。你的方法似乎坏了。
  • 我建议您从 Label 派生的控件开始,在 Themes/Generic.xaml 中使用标准默认样式,在其中声明一个 ControlTemplate,其中包含一个 Border 内的 ContentPresenter。
  • 更简单的是,根本不创建派生控件类。只需声明适当的样式和控制模板,例如对于标签类。见Control authoring overview

标签: c# wpf properties dependencies


【解决方案1】:

不确定您到底想要实现什么,但始终在Border 内使用Label 来可视化其Content 的UserControl 应该通过其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>

【讨论】:

    猜你喜欢
    • 2013-02-09
    • 1970-01-01
    • 2012-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-19
    • 2015-11-26
    • 1970-01-01
    相关资源
    最近更新 更多