BigFunger
BigFunger

Reputation: 174

Wpf: setting IsEnabled in code behind breaks Style Trigger

I am having an issue when using a DataTrigger to manipulate the IsEnabled property of a control. Normally it works fine, however when I initialize the IsEnabled state within the View's Initialized event, the dynamic stylizing no longer works.

Here's my code. I trimmed it down to the simplest example I could.

Why is this occurring, and what can I do to allow me to set IsEnabled both by a style trigger and by initializing it in the code behind?

Thanks in advance!

View:

(Contains a textbox that should be enabled/disabled depending on the value of a checkbox)

<Window x:Class="IsEnabled.Views.MainView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Initialized="Window_Initialized">
    <StackPanel Orientation="Vertical">
        <TextBox x:Name="txtTarget" Width="200">
            <TextBox.Style>
                <Style TargetType="{x:Type TextBox}">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Path=ToggleValue}" Value="True">
                            <Setter Property="IsEnabled" Value="False" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </TextBox.Style>
        </TextBox>
        <CheckBox x:Name="chkSource" IsChecked="{Binding Path=ToggleValue}" />
    </StackPanel>
</Window>

View Codebehind:

(The only addition is the implementation of the Initialized event setting the inital state for IsEnabled)

using System;
using System.Windows;

namespace IsEnabled.Views
{
    public partial class MainView : Window
    {
        public MainView()
        {
            InitializeComponent();
        }

        private void Window_Initialized(object sender, EventArgs e)
        {
            txtTarget.IsEnabled = false;
        }
    }
}

ViewModel:

(ViewModelBase holds the implementation of the INotifyPropertyChanged interface)

using System;

namespace IsEnabled.ViewModels
{
    class MainViewModel : ViewModelBase
    {
        private bool _ToggleValue;
        public bool ToggleValue
        {
            get { return _ToggleValue; }
            set
            {
                _ToggleValue = value;
                OnPropertyChanged(this, "ToggleValue");
            }
        }
    }
}

Upvotes: 2

Views: 3217

Answers (1)

dowhilefor
dowhilefor

Reputation: 11051

Have a look at dependency property value precedence, and how changing values from different places, Styles, Triggers, Animations etc. work together.

Add to your Binding Mode=TwoWay and it should work.

Upvotes: 2

Related Questions