Ksice
Ksice

Reputation: 3327

XAML: setup property from parent view?

I have button custom view:

<UserControl>
...
<Rectangle x:Name="Highlight" Style="{DynamicResource HighlightStyle}"/>
...
<DataTrigger Binding="{Binding Path=IsHighlighted}" Value="true">
                                    <Setter TargetName="Highlight" Property="Opacity" Value="1"/>
                                </DataTrigger>
...
</UserControl>

And button is used in parent view like next:

<local:MyButton x:Name="Btn1" DataContext="{Binding Path=Btn1}" />

So when I need button to be highlighted I'm doing this from code. Like Btn1.IsHighlighted=true; But at some point I need to setup this directly from parent XAML. Is it possible?

I.e. on some specific view I don't want Btn1.IsHighlighted to be used. Instead I want something like this:

<local:MyButton x:Name="Btn1" DataContext="{Binding Path=Btn1}" IsHighlighted="true" />

Upvotes: 2

Views: 66

Answers (1)

romerotg
romerotg

Reputation: 464

You can register the IsHighlighted as an property of your MyButton class

private static readonly DependencyProperty IsHighlightedProperty = DependencyProperty.Register
(
    "IsHighlighted",
    typeof(bool),
    typeof(MyButton),
    new PropertyMetadata((bool)false)
);

public bool IsHighlighted
{
    get { return (bool) GetValue(IsHighlightedProperty); }
    set { SetValue(IsHighlightedProperty, value); }
}

EDIT adding XAML use

Your MyButton XAML should have something like this

<Rectangle x:Name="Highlight" Width="100">
    <Rectangle.Style>
        <Style TargetType="Rectangle">
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsHighlighted}" Value="True">
                    <Setter Property="Opacity" Value="1" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Rectangle.Style>
</Rectangle>

I actually tested Property="Fill" and Value="Green" here. But changed to match your case.

The parent view should have

<local:MyButton x:Name="Btn1" DataContext="{Binding Path=Btn1}" IsHighlighted="true" />

Upvotes: 5

Related Questions