Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the style of a button based on if else using DataTriggers in wpf mvvm

I want to change the style of the button on the basis of if else condition when first the wpf application is getting loaded. On application loaded using if, there will be one style of button and in else part, there will be another. How to achieve this using Datatriggers or else using MVVM pattern.

Kindly Suggest?

Thanks

like image 348
Tarun Avatar asked Apr 13 '11 06:04

Tarun


2 Answers

You can use Style.Setters to set default value. For other determined conditions use Style.Triggers. This works like if else.

<TextBlock.Style>
    <Style TargetType="TextBlock">
        <Style.Triggers>
            <DataTrigger Binding="{Binding ElementName=EditorWindow, Path=Category}" Value="R">
                <Setter Property="Visibility" Value="Visible"/>
            </DataTrigger>
        </Style.Triggers>
        <Style.Setters>
            <Setter Property="Visibility" Value="Collapsed"/>
        </Style.Setters>
    </Style>
</TextBlock.Style>
like image 71
Sergii Avatar answered Nov 10 '22 09:11

Sergii


You should look into Data Templates and a Template Selector. Here is a hastily copy pasted example from my own code, it's not immediately applicable to buttons but I think it should help you along your way.

The following is from the application resources xaml file. I use it to decide which view to use for the ProjectViewModel based on a variable in the ViewModel:

    <DataTemplate DataType="{x:Type viewmod:ProjectViewModel}">
    <DataTemplate.Resources>
        <DataTemplate x:Key="ProjectEditViewTemplate">
            <view:ProjectEditView/>
        </DataTemplate>
        <DataTemplate x:Key="ServiceSelectionViewTemplate">
            <view:ServiceSelectionView/>
        </DataTemplate>
    </DataTemplate.Resources>
    <ContentControl Content="{Binding}" ContentTemplateSelector="{StaticResource ProjectViewModelTemplateSelector}" />
</DataTemplate>

The ProjectViewModelTemplateSelector is defined as follows:

    public class ProjectViewModelTemplateSelector : DataTemplateSelector
{
    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        FrameworkElement element = container as FrameworkElement;

        if (element != null && item != null && item is ViewModel.ProjectViewModel)
        {
            if ((item as ViewModel.ProjectViewModel).EditMode)
            {
                return element.FindResource("ProjectEditViewTemplate") as DataTemplate;
            }
            else
            {
                return element.FindResource("ServiceSelectionViewTemplate") as DataTemplate;
            }

        }
        else
            return base.SelectTemplate(item, container);
    }

}

}

like image 3
Pieter Müller Avatar answered Nov 10 '22 10:11

Pieter Müller