Sylvain B.
Sylvain B.

Reputation: 739

User control parameter in wpf mvvm

I want to create a user control with a bool parameter that defines a dynamic behavior, using MVVM pattern, so I can use the user control in another view that way :

<local:MyUserControl BoolParam={Binding aBoolBinding} />

About the coding of the user control, the xaml should use the value of BoolParam to do something like this :

...
<TextBox>
    <TextBox.Style>
        <Style TargetType="TextBox">
            <Style.Trigger>
                <DataTrigger Binding="{referenceToBoolParam}" Value="False" >
                    <Setter Property="Visibility" Value="Collapsed" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBox.Style>
</TextBox>
...

Am I supposed to define a property

public bool BoolParam { get; set; }

in the code-behind of the user control, and to code the logic associated to this parameter in the ViewModel of the user control ? Actually I am a bit confused about it, what is the good practice ?

Upvotes: 0

Views: 1623

Answers (1)

mm8
mm8

Reputation: 169350

BoolParam should be a dependency property for you to be able to bind something to it. You define this in the code-behind of MyUserControl:

public bool BoolParam
{
    get { return (bool)this.GetValue(BoolParamProperty); }
    set { this.SetValue(BoolParamProperty, value); }
}

public static readonly DependencyProperty BoolParamProperty = DependencyProperty.Register(
  "BoolParam", typeof(bool), typeof(MyUserControl), new PropertyMetadata(false));

You could then set the DataContext of the UserControl to an instance of a view model that contains a public bool property called aBoolBinding and bind to this one as usual.

View Model:

private bool _b;
public bool aBoolBinding
{
    get
    {
        return _b;
    }

    set
    {
        _b = value;
        NotifyPropertyChanged();
    }
}

View:

<local:MyUserControl BoolParam="{Binding aBoolBinding}" />

This is how data binding works. A target property in the views is bound to a source property of a view model.

Edit:

This binds to the BoolParam property of the UserControl from a TextBox style defined in the UserControl:

<TextBox>
    <TextBox.Style>
        <Style TargetType="TextBox">
            <Style.Triggers>
                <DataTrigger Binding="{Binding BoolParam, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="False" >
                    <Setter Property="Visibility" Value="Collapsed" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBox.Style>
</TextBox>

Upvotes: 1

Related Questions