简体   繁体   中英

WPF: Set a property value from another property value at design time

I have created a custom control from a Label. I have added a new dependency property "MyCaption". I made the Content proeprty as hidden:

[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new string Content { get; set; }

Now, I want this behaviour: if I set MyCaption value, I want Content is set with that value too, at design time.

Some ideas?

EDIT: I tried to define my dependency property like this, but it doesn't work:

public static readonly DependencyProperty MyCaptionProperty =
    DependencyProperty.Register("MyCaption ",
                                typeof(string),
                                typeof(TMSLabel));

    [Description("Valore della label"), Category("MyProperties")] 
    public string MyCaption 
    {
        get { return (string)GetValue(MyCaptionProperty); }
        set { 
            SetValue(MyCaptionProperty, value);
            Content = value;
        }
    }

HINT: If I remove the code that made che Content property as hidden, the code above works!

From - http://wpftutorial.net/DependencyProperties.html

Important: Do not add any logic to these properties, because they are only called when you set the property from code. If you set the property from XAML the SetValue() method is called directly.

So, trying to set Content property from the Dependency Property setting doesn't sounds right.

How about try to use the PropertyChangedCallBack instead

public class MyLabel : Label
{
    public static readonly DependencyProperty MyCaptionProperty =
        DependencyProperty.Register("MyCaption ",
                                    typeof(string),
                                    typeof(MyLabel), new FrameworkPropertyMetadata(string.Empty, OnChangedCallback));

    public string MyCaption
    {
        get { return (string)GetValue(MyCaptionProperty); }
        set { SetValue(MyCaptionProperty, value); }
    }

    private static void OnChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var labelControl = d as Label;
        if (labelControl != null)
            labelControl.Content = e.NewValue;
    }
}

<Window x:Class="WpfTestProj.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:wpfTestProj="clr-namespace:WpfTestProj"        
    Title="MainWindow" Height="350" Width="525">
<wpfTestProj:MyLabel MyCaption="This is a test" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM