【问题标题】:UserControl custom DependencyProperties problemUserControl自定义DependencyProperties问题
【发布时间】:2009-03-26 19:52:08
【问题描述】:

我有一个带有图像和标签的自定义 UserControl,两者都是在设计时在 XAML 中设置的,如下所示:<controls:HomeBarButton Icon="/SuCo;component/Resources/music.png" Text="music"/>

当控件只有一个图标时,它看起来很好。当我添加 Text 属性时,图标在设计和运行时都会消失,并且文本标签会忽略 UserControl 中设置的格式,并且当标签居中时,在控件的左上角只是黑色。

相关的用户控件 XAML:

    <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
    <Image x:Name="icon" Width="102" Height="102" VerticalAlignment="Stretch"  Source="{Binding Icon}"/>
    <Label x:Name="label" HorizontalContentAlignment="Center" VerticalAlignment="Bottom" Foreground="White" FontFamily="Calibri" FontSize="24" Padding="0" Content="{Binding Text}"></Label>
</StackPanel>

代码隐藏:

        public ImageSource Icon
    {
        get { return (ImageSource)this.GetValue(IconProperty); }
        set { this.SetValue(IconProperty, value); }
    }

    public static readonly DependencyProperty IconProperty = DependencyProperty.Register("Icon", typeof(ImageSource), typeof(HomeBarButton), new FrameworkPropertyMetadata(OnIconChanged));

    private static void OnIconChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
    {
        dependencyObject.SetValue(Image.SourceProperty, e.NewValue);
    }

    public string Text
    {
        get { return (string)this.GetValue(TextProperty); }
        set { this.SetValue(TextProperty, value); }
    }

    public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(HomeBarButton), new FrameworkPropertyMetadata(OnTextChanged));

    private static void OnTextChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
    {
        dependencyObject.SetValue(Label.ContentProperty, e.NewValue);
    }

我做错了什么? :(

【问题讨论】:

    标签: wpf user-controls dependency-properties


    【解决方案1】:

    首先,我将该 Label 更改为 TextBlock——您将使用 Label 将标签的文本与另一个控件相关联。从您的代码看来,您没有这样做,只想显示文本。要检查的另一件事是您的文本是否显示在图标的顶部。我猜这就是正在发生的事情。更改为 TextBlock 可能会解决此问题,如果没有,您可能应该手动设置 TextBlock 的高度和 with。只是我的 0.02 价值。

    【讨论】:

    • 啊,是的,确实切换到 TextBlock 控件有效! :) 谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    • 2012-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多