States
States

Reputation: 548

DataTriggers in WinRT

As I understand DataTriggers are not supported in WinRT. But, how does one work around this?

I have a model that has a "Selected" property implemented, extending INotifyPropertyChanged. I would like to change the border of the button to Red if Selected is True. I just don't know how to link a property change into triggering a state change.

Model

class MyObject : INotifyPropertyChanged
{
    public MyObject()
    {
        Selected = true;
    }

    private bool _selected;

    public bool Selected
    {
        get { return _selected; }
        set { _selected = value; OnPropertyChanged("Selected"); }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

XAML

<Grid>
    <Button Margin="131,97,171,124" Content="Hello!" DataContext="MyObject" d:DataContext="{d:DesignInstance local:MyObject}">
        <Button.Template>
            <ControlTemplate TargetType="Button">
                <Border BorderThickness="1">
                    <Border.BorderBrush>
                        <SolidColorBrush Color="Aqua"/>
                    </Border.BorderBrush>
                    <StackPanel>
                        <TextBlock Text="{TemplateBinding Content}"/>
                        <TextBlock Text="{Binding Selected}"/>
                    </StackPanel>
                </Border>
            </ControlTemplate>
        </Button.Template>
    </Button>
</Grid>

Upvotes: 2

Views: 537

Answers (2)

Mark
Mark

Reputation: 14930

You can use a simple converter (IValueConverter). Then bind the border property to the Selected property in your ViewModel:

<Border BorderBrush="{Binding Selected, Converter={StaticResource MyConverter}}">

you will of course need to put a resource somewhere in your Page resources, or the App resource dictionary:

<mynamespace:MyConverter x:Key="MyConverter"/>

Then in the converter, check if the value is True and return a red colour brush

(I did just quickly write this, didnt test it but you can Google how to do this stuff easily as well)

Upvotes: 1

Related Questions