[Solved] how to write an user control for WPF XAML [duplicate]


I would use a Custom Control and not a User Control and make the default child a custom DependencyProperty and add to the control’s content manually

[ContentProperty("ConditionalContent")]
public partial class If : ContentControl
{
    public If()
    {
        Loaded += OnLoad;
    }

    private void OnLoad(object sender, RoutedEventArgs e)
    {
        update();
    }

    private void update()
    {
        Content = Condition ? ConditionalContent : null;
    }

    // === component properties

    // omg, WPF
    public bool Condition
    {
        get { return (bool)GetValue(ConditionProperty); }
        set { SetValue(ConditionProperty, value); }
    }

    public static readonly DependencyProperty ConditionProperty = DependencyProperty.Register("Condition", typeof(bool), typeof(If), new PropertyMetadata(OnConditionChangedCallback));

    private static void OnConditionChangedCallback(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        if (sender is If s)
        {
            s.update();
        }
    }



    public object ConditionalContent
    {
        get { return (object)GetValue(ConditionalContentProperty); }
        set { SetValue(ConditionalContentProperty, value); }
    }

    public static readonly DependencyProperty ConditionalContentProperty =
        DependencyProperty.Register("ConditionalContent", typeof(object), typeof(If), new PropertyMetadata(null,OnConditionChangedCallback));


}

and it works like this

<local:If Condition="{Binding}">
    sdgdfhsh <!-- or anything else! -->
</local:If>

4

solved how to write an user control for WPF XAML [duplicate]