tags:

views:

18

answers:

1

Hi all,

Simple WPF question I have a text Box and an OK Button and I am using a MVVM pattern. All I want to do is enable OK button only when textBox.Length > 0.

But what I get is only when the textBox loses focus the button is enabled.

Am I missing something?

I have bound the datacontext to the viewmodel and done the following. Why does it not work?

Thanks for your help

XAML

<TextBox Grid.Column="1" 
              Grid.Row="2" 
             Margin="4" 
             Name="txtName" Text="{Binding Path=Name}"/>

      <Button x:Name="btnOK" 
                            MinWidth="70" Padding="3.5" 
                            Margin="3.5" 
                            Grid.Column="1" 
                            Content="OK" 
                            Click="OnOk"
                            Command="{Binding Path=OKCommand}"
                            VerticalAlignment="Center" 
                            HorizontalAlignment="Left" IsDefault="True" />

In view Model

         public class TestViewModel : ViewModelBase
            {
                private string _name;

                public string Name
                {
                    get { return _name; }
                    set
                    {
                        _name = value;
                        OnPropertyChanged("Name");
                    }
                }
                private RelayCommand _OkCommand;
                public ICommand OKCommand
                {
                    get
                    {
                        return _OkCommand ?? (_OkCommand = new RelayCommand(x => Execute(), x => CanExecute));
                    }
                }
                private bool CanExecute
                {
                    get
                    {
                        return !string.IsNullOrEmpty(Name);            
                    }
                }
                private void Execute()
                {
                    //do something here
                }
+2  A: 

Exchange this line:

Text="{Binding Path=Name}"

With

Text="{Binding Path=Name,UpdateSourceTrigger=PropertyChanged}"

That way the binding will update everytime the Text-property changes. Default for the Text Property of TextBox is LostFocus.

Goblin
Thanks a lot it worked