MemphiZ
MemphiZ

Reputation: 776

Set Visibility of control based on custom DependencyProperty

I have a UserControl which contains the following XAML:

<GroupBox>
    <Grid>
        <Button x:Name="btn" Content="Test"/>
        <TextBlock x:Name="txt" Visibility="Collapsed"/>
    </Grid>
</GroupBox>

I've added a DependencyProperty of type enum using this code:

public static readonly DependencyProperty DisplayTypeProperty = DependencyProperty.Register("DisplayType", typeof(DisplayTypeEnum), typeof(myUserControl), new PropertyMetadata(default(DisplayTypeEnum.Normal)));

    public DisplayTypeEnum DisplayType
    {
        get
        {
            return (DisplayTypeEnum)this.Dispatcher.Invoke(DispatcherPriority.Background, (DispatcherOperationCallback)delegate
            { return GetValue(DisplayTypeProperty); }, DisplayTypeProperty);

        }
        set
        {
            this.Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate
            { SetValue(DisplayTypeProperty, value); }, value);
        }
    }

Now I would like to be able to set the Visibility of both Controls based on my DependencyProperty.

I've already tried adding the following Trigger but I get 3 errors:

<UserControl.Triggers>
<Trigger Property="DisplayType" Value="Text">
            <Setter Property="Visibility" TargetName="btn" Value="Collapsed"/>
            <Setter Property="Visibility" TargetName="txt" Value="Visible"/>
</Trigger>
</UserControl.Triggers>

The first error states that the member "DisplayType" is not recognized or accessible. The other two tell me that the controls (txt and btn) are not recognized. What am i doing wrong?

Thanks in advance!

Upvotes: 0

Views: 2369

Answers (1)

Dante
Dante

Reputation: 3316

You could use a callBack

public static readonly DependencyProperty DisplayTypeProperty = DependencyProperty.Register("DisplayType", typeof(DisplayTypeEnum), typeof(myUserControl), new PropertyMetadata(YourDPCallBack));

private static void YourDPCallBack(DependencyObject instance, DependencyPropertyChangedEventArgs args)
{
     YourUserControl control =   (YourUserControl)instance;
     // convert your Display enum to visibility, for example: DisplayType dT = args.NewValue
     // Or do whatever you need here, just remember this method will be executed everytime
     // a value is set to your DP, and the value that has been asigned is: args.NewValue
     // control.btn.Visibility = dT;
     // txt.Visibility = dT;
}

I hope it helps,

Regards

Upvotes: 2

Related Questions