This is MVVM application. There is a window and related view model class.
There is TextBox, Button and ListBox on form. Button is bound to DelegateCommand that has CanExecute function. Idea is that user enters some data in text box, presses button and data is appended to list box.
I would like to enable command (and button) when user enters correct data in TextBox. Things work like this now:
CanExecute() method contains code that checks if data in property bound to text box is correct.
Text box is bound to property in view model
UpdateSourceTrigger is set to PropertyChanged and property in view model is updated after each key user presses.
Problem is that CanExecute() does not fire when user enters data in text box. It doesn't fire even when text box lose focus.
How could I make this work?
Edit:
Re Yanko's comment:
Delegate command is implemented in MVVM toolkit template and when you create new MVVM project, there is Delegate command in solution. As much as I saw in Prism videos this should be the same class (or at least very similar).
Here is XAML snippet:
...
<UserControl.Resources>
<views:CommandReference x:Key="AddObjectCommandReference"
Command="{Binding AddObjectCommand}" />
</UserControl.Resources>
...
<TextBox Text="{Binding ObjectName, UpdateSourceTrigger=PropertyChanged}"> </TextBox>
<Button Command="{StaticResource AddObjectCommandReference}">Add</Button>
...
View model:
// Property bound to textbox
public string ObjectName
{
get { return objectName; }
set {
objectName = value;
OnPropertyChanged("ObjectName");
}
}
// Command bound to button
public ICommand AddObjectCommand
{
get
{
if (addObjectCommand == null)
{
addObjectCommand = new DelegateCommand(AddObject, CanAddObject);
}
return addObjectCommand;
}
}
private void AddObject()
{
if (ObjectName == null || ObjectName.Length == 0)
return;
objectNames.AddSourceFile(ObjectName);
OnPropertyChanged("ObjectNames"); // refresh listbox
}
private bool CanAddObject()
{
return ObjectName != null && ObjectName.Length > 0;
}
As I wrote in the first part of question, following things work:
property setter for ObjectName is triggered on every keypress in textbox
if I put return true; in CanAddObject(), command is active (button to)
It looks to me that binding is correct.
Thing that I don't know is how to make CanExecute() fire in setter of ObjectName property from above code.
Re Ben's and Abe's answers:
CanExecuteChanged() is event handler and compiler complains:
The event
'System.Windows.Input.ICommand.CanExecuteChanged'
can only appear on the left hand side
of += or -=
there are only two more members of ICommand: Execute() and CanExecute()
Do you have some example that shows how can I make command call CanExecute().
I found command manager helper class in DelegateCommand.cs and I'll look into it, maybe there is some mechanism that could help.
Anyway, idea that in order to activate command based on user input, one needs to "nudge" command object in property setter code looks clumsy. It will introduce dependencies and one of big points of MVVM is reducing them.
Edit 2:
I tried to activate CanExecute by calling addObjectCommand.RaiseCanExecuteChanged() to ObjectName property setter from above code. This does not help either. CanExecute() is fired few times when form is initialized, but after that it never gets executed again. This is the code:
// Property bound to textbox
public string ObjectName
{
get { return objectName; }
set {
objectName = value;
addObjectCommand.RaiseCanExecuteChanged();
OnPropertyChanged("ObjectName");
}
}
Edit 3: Solution
As Yanko Yankov and JerKimball wrote, problem is static resource. When I changed button binding like Yanko suggested:
<Button Command="{Binding AddObjectCommand}">Add</Button>
things started to work immediately. I don't even need RaiseCanExecuteChanged(). Now CanExecute fires automatically.
Why did I use static resource in first place?
Original code was from WPF MVVM toolkit manual. Example in that manual defines commands as static resource and then binds it to menu item. Difference is that instead of string property in my example, MVVM manual works with ObservableCollection.
Edit 4: Final explanation
I finally got it. All I needed to do was to read comment in CommandReference class. It says:
/// <summary>
/// This class facilitates associating a key binding in XAML markup to a command
/// defined in a View Model by exposing a Command dependency property.
/// The class derives from Freezable to work around a limitation in WPF when
/// databinding from XAML.
/// </summary>
So, CommandReference is used for KeyBinding, it is not for binding in visual elements. In above code, command references defined in resources would work for KeyBinding, which I don't have on this user control.
Of course, sample code that came with WPF MVVM toolkit were correct, but I misread it and used CommandReference in visual elements binding.
This WPF MVVM really is tricky sometimes.
Things look much clearer now with the edits, thanks! This might be a stupid question (I'm somewhat tired of a long day's work), but why don't you bind to the command directly, instead of through a static resource?
<Button Command="{Binding AddObjectCommand}">Add</Button>
Since you are using the DelegateCommand, you can call it's RaiseCanExecuteChanged method when your text property changes. I'm not sure what you are trying to accomplish with your CommandReference resource, but typically you just bind the commands directly to the button element's Command property:
<TextBox Text="{Binding ObjectName, UpdateSourceTrigger=ValueChanged}" />
<Button Command="{Binding AddObjectCommand}" Content="Add" />
This would be the relevant portion of your view model:
public string ObjectName
{
get { return objectName; }
set
{
if (value == objectName) return;
value = objectName;
AddObjectCommand.RaiseCanExecuteChanged();
OnPropertyChanged("ObjectName");
}
}
Try raising CanExecuteChanged when your property changes. The command binding is really distinct from the property binding and buttons bound to commands are alerted to a change in status by the CanExecuteChanged event.
In your case, you could fire a check when you do the PropertyChanged on the bound property that would evaluate it and set the command's internal CanExecute flag and then raise CanExecuteChanged. More of a "push" into the ICommand object than a "pull".
Echoing Abe here, but the "right" path to take here is using:
public void RaiseCanExecuteChanged();
exposed on DelegateCommand. As far as dependencies go, I don't think you're really doing anything "bad" by raising this when the property that the command depends on changes within the ViewModel. In that case, the coupling is more or less contained wholly within the ViewModel.
So, taking your above example, in your setter for "ObjectName", you would call RaiseCanExecuteChanged on the command "AddObjectCommand".
I know this is an old question but I personally think it's easier to bind the textbox Length to button's IsEnabled property, e.g.:
<TextBox Name="txtbox" Width="100" Height="30"/>
<Button Content="SomeButton " Width="100" Height="30"
IsEnabled="{Binding ElementName=txtbox, Path=Text.Length, Mode=OneWay}"></Button>
If ElementName binding does not work, use:
<Entry x:Name="Number1" Text="{Binding Number1Text}" Keyboard="Numeric"></Entry>
<Entry x:Name="Number2" Text="{Binding Number2Text}" Keyboard="Numeric"></Entry>
<Button Text="Calculate" x:Name="btnCalculate" Command="{Binding CalculateCommand}" IsEnabled="{Binding Source={x:Reference Number1, Number2}, Path=Text.Length, Mode=OneWay}"></Button>
or use:
<Entry x:Name="Number1" Text="{Binding Number1Text}" Placeholder="Number 1" Keyboard="Numeric"></Entry>
<Entry x:Name="Number2" Text="{Binding Number2Text}" Placeholder="Number 2" Keyboard="Numeric"></Entry>
<Button VerticalOptions="Center" Text="Calculate" x:Name="btnCalculate" Command="{Binding CalculateCommand}">
<Button.Triggers>
<DataTrigger TargetType="Button"
Binding="{Binding Source={x:Reference Number1, Number2},
Path=Text.Length}"
Value="{x:Null}">
<Setter Property="IsEnabled" Value="False" />
</DataTrigger>
</Button.Triggers>
Related
I have read some thread about how to work on WPF ListView command binding.
Passing a parameter using RelayCommand defined in the ViewModel
Binding Button click to a method
Button Command in WPF MVVM Model
How to bind buttons in ListView DataTemplate to Commands in ViewModel?
All of them suggest write the logic code inside ViewModel class, for example:
public RelayCommand ACommandWithAParameter
{
get
{
if (_aCommandWithAParameter == null)
{
_aCommandWithAParameter = new RelayCommand(
param => this.CommandWithAParameter("Apple")
);
}
return _aCommandWithAParameter;
}
}
public void CommandWithAParameter(String aParameter)
{
String theParameter = aParameter;
}
It is good practice or anyway so I can move the CommandWithAParameter() out of the ViewModel?
In principle, MVVM application should be able to run to its full potential without creating the views. That's impossible, if some parts of your logic are in View classes.
On top of that, ICommand has CanExecute, which will autamagically disable buttons, menu items etc. if the command should not be run.
I understand why with basic RelayCommand implementation it can be hard to see the benefits, but take a look at ReactiveCommand samples.
ReactiveCommand handles async work very well, even disabling the button for the time work is done and enabling it afterwards.
Short example: you have a login form. You want to disable the login button if the username and password are empty.
Using commands, you just set CanExecute to false and it's done.
Using events, you have manualy disable/enable the button, remember that it has to be done in Dispatcher thread and so on - it gets very messy if you have 5 buttons depending on different properties.
As for ListView, commands are also usefull - you can bind current item as command parameter:
<ListView ItemsSource="{Binding MyObjects}">
<ListView.ItemTemplate>
<DataTemplate>
<DockPanel>
<!-- change the context to parent ViewModel and pass current element to the command -->
<Button DockPanel.Dock="Right" Command="{Binding ElementName=Root, Path=ViewModel.Delete}" CommandParameter="{Binding}">Delete</Button>
<TextBlock Text="{Binding Name}"/>
</DockPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
1) Using MVVM Light, I have an xCeed datagrid which I only want visible only after the user has opened a file.
So I've created a boolean property in the ViewModel and use the booleantoVisibilityConverter to parse that property
<Window.Resources>
<BooleanToVisibilityConverter x:Key="booleanToVisibilityConverter" />
So in the (lengthy so I'm cutting off the beginning it) xaml I put on the datagrid, I added this to the end:
Visibility="{Binding Path=FileOpened, Converter={StaticResource booleanToVisibilityConverter}}">
The moment I put that to use though, the grid disappears from the designtime view, which I do not want.
Checking to see if I'm in Design View inside the property's accessor doesn't seem to help.
public bool FileOpened
{
get
{
if (IsInDesignMode)
return true;
return fileOpened;
}
set => fileOpened = value;
}
EDIT: I've also tried to call RaisePropertyChanged on the mutator. Didn't expect it to help and, sure enough, it didn't.
I have a serious issue with binding any command to my user control. Everything compiles, but the command is never called. I have tried two approaches - first, I tried to bind the command to a button inside my control, and when I was unable to do it, I tried to bind the command to an inputcommand of the control itself to see if it would work. It didn't. The control itself is within an ItemsControl, in case that matters.
Here's a simplified version of what I did. In the xaml.cs file of the control:
public static readonly DependencyProperty CloseCommandProperty = DependencyProperty.Register(
"CloseCommand",
typeof(ICommand),
typeof(Thumbnail),
new UIPropertyMetadata(null)
);
public ICommand CloseCommand
{
get { return (ICommand)GetValue(CloseCommandProperty); }
set { SetValue(CloseCommandProperty, value); }
}
In the UserControl's xaml file, the offending button (the UserControl has Name="Control", and Hash is another dependency property):
<Button Command="{Binding ElementName=Control, Path=CloseCommand}" CommandParameter="{Binding ElementName=Control, Path=Hash}">
<TextBlock Text="X"/></Button>
Now, a simplified (irrelevant properties not included) datatemplate part of the xaml file of the view (which has a datacontext, if that matters), where I use this control:
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:Thumbnail Hash="{Binding Hash}"
CloseCommand="{Binding ElementName=Control, Path=DataContext.RemoveImageCommand}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
Just for the sake of completeness, I'll include the command from the viewmodel.
private bool CanRemoveImageCommandExecute(string hash)
{
return true;
}
private void RemoveImageCommandExecute(string hash)
{
MessageBox.Show("ABC","ABC");
}
public ICommand RemoveImageCommand
{
get { return new RelayCommand<string>(RemoveImageCommandExecute, CanRemoveImageCommandExecute);}
}
The RelayCommand class comes from MicroMVVM, and it just creates a command from two functions (and works everywhere else).
Can you tell me why clicking the button does nothing and how to fix it?
It seems that, even though I wasted a few hours on that, I was too quick to ask the question. Literally a few minutes after posting it, I realized that my binding in ItemTemplate is wrong.
The problem was that I used ElementName instead of RelativeSource:
CloseCommand="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=local:AddImage}
Where local:AddImage is the name of the view which has the DataContext set to the viewmodel..
I am trying to figure out the best way to select all the text in a TextBox the first time the control is loaded. I am using the MVVM pattern, so I am using two-way binding for the Text property of the TextBox to a string on my ViewModel. I am using this TextBox to "rename" something that already has a name, so I would like to select the old name when the control loads so it can easily be deleted and renamed. The initial text (old name) is populated by setting it in my ViewModel, and it is then reflected in the TextBox after the data binding completes.
What I would really like to do is something like this:
<TextBox x:Name="NameTextBox" Text="{Binding NameViewModelProperty, Mode=TwoWay}" SelectedText="{Binding NameViewModelProperty, Mode=OneTime}" />
Basically just use the entire text as the SelectedText with OneTime binding. However, that does not work since the SelectedText is not a DependencyProperty.
I am not completely against adding the selection code in the code-behind of my view, but my problem in that case is determining when the initial text binding has completed. The TextBox always starts empty, so it can not be done in the constructor. The TextChanged event only seems to fire when a user enters new text, not when the text is changed from the initial binding of the ViewModel.
Any ideas are greatly appreciated!
Dan,
I wrote a very simple derived class, TextBoxEx, that offers this functionality. The TextBoxEx class derives from TextBox, and can be referenced in XAML for any and all of your TextBox’s. There are no methods to call. It just listens for Focus events and selects it own text. Very simple.
Usage is as follows:
In XAML, reference the assembly where you implement the TextBoxEx class listed below, and add as many TextBoxEx elements as you need. The example below uses data binding to display a username.
<UserControl x:Class="MyApp.MainPage"
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:ClassLibrary;assembly=ClassLibrary"
>
.
.
.
<c:TextBoxEx x:Name="NameTextBox" Text="{Binding NameViewModelProperty, Mode=TwoWay}" Width="120" />
This code below works with Silverlight 3.
using System.Windows;
using System.Windows.Controls;
namespace ClassLibrary
{
// This TextBox derived class selects all text when it receives focus
public class TextBoxEx : TextBox
{
public TextBoxEx()
{
base.GotFocus += OnGotFocus;
}
private void OnGotFocus(object sender, RoutedEventArgs e)
{
base.SelectAll();
}
}
}
Good luck.
I'm leaving Jim's solution as the answer, since calling SelectAll() on the GotFocus event of the TextBox did the trick.
I actually ended up making a Blend TriggerAction and an EventTrigger to do this instead of subclassing the TextBox or doing it in code-behind. It was really simple to do and nice to be able to keep the behavior logic encapsulated and just add it declaratively in XAML to an existing TextBox.
Just posting this in case anyone else comes across this thread and is interested:
XAML:
<TextBox x:Name="NameTextBox" Text="{Binding NameViewModelProperty, Mode=TwoWay}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="GotFocus">
<local:SelectAllAction/>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
C#
public class SelectAllAction : TriggerAction<TextBox>
{
protected override void Invoke(object parameter)
{
if (this.AssociatedObject != null)
{
this.AssociatedObject.SelectAll();
}
}
}
Just wanna add a link I found pertaining to this - here is a fantastic discussion (read comments) on Behaviours vs subclassing vvs attached properties...
At first I want to say that sample below is oversimplification.
Suppose you have bound WPF control.
<Window Title="Window1" Height="300" Width="300">
<Grid>
<StackPanel>
<TextBox Text="{Binding Name}" Margin="10"/>
<Button HorizontalAlignment="Center"
Content="Click Me" Margin="5"
Padding="2" Click="OnButtonClick" />
</StackPanel>
</Grid>
</Window>
Window is bound to the Person class which implements INotifyPropertyChanged and has Name setter in form
public string Name
{
get { return _name; }
set
{
_name = "Some Name";
OnPropertyChanged("Name");
}
}
I.e. _name is assigned "Some Name" whenever user tries to change it from UI.
But this sample does not works. I changed name in TextBox to some value press tab forcing focus to move to the Button and value in TextBox remains unchanged although PropertyChanged event was triggered.
Could you please explain me why it happens? As I understand PropertyChanged event forces UI to reread values from properties and display them but in my example value in databound textbox is not updated.
Again. I understand that this is poor implementation of the property and but I want to repeat that this is oversimplification.
It is just a sample.
But anyway, PropertyChanged signals that property was changed and should be updated but it does not.
The PropertyChanged event is ignored by the TextBox because it is the initiator of the event.
Some clarification:
The TextBox (or the binding on the textbox) knows it is the initiator because it receives the PropertyChanged event in the same call. By doing an asynchronous call, the textbox (or binding) has no way to know that it is the initiator, so it will process the event as if someone else has updated it
If you add a 2nd textbox to your UI, you'll see that the 2nd TextBox does change when you edit the 1st, and the other way around.
The dummy converter workaround suggested by Heinzi (described here) doesn't work when binding's UpdateSourceTrigger is PropertyChanged. But what if this is what we need?
It seems that making the binding asynchrounous does the trick, e.g.:
SelectedIndex="{Binding SelectedIndex, IsAsync=True}"
As Bubblewrap already pointed out, this is by design -- the textbox assumes that if it sets a bound property to some value, the setter will not change the value. According to Microsoft, they won't change this behavior since this would break existing code.
If you want to change the value (yes, there are perfectly good reasons for doing that), you have to use a workaround, for example, by adding a dummy converter. There is a blog entry (not written by me) describing this technique in detail.
The reason is because you have hardcoded the 'Some Name' in the setter. When you changed the textBox value the setter is actually getting called and it again setting "Some Name" as the propertyValue so it doesnt seems to be changed in the UI.
Put _name = value and things will just work as you expected,
public string MyField
{
get { return _myField; }
set {
if (_myField == value)
return;
_myField = value;
OnPropertyChanged("MyField");
}
}
This is the proper implementation of the property.
When you change the property, make sure that the EXACT same instance of the object is binded to a control. Otherwise, the change will be notified but the control will never get it because the control is not binded properly.
Replacing setter in form
set
{
_name = "Some Name";
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.DataBind,
(SendOrPostCallback)delegate { OnPropertyChanged("Name"); },
null);
}
resolves the issue but it is still open. Why should I make async call instead of synchronous signaling that my property has been changed.
If I am not mistaken, the default binding behavior of the Text property on the TextBox is TwoWay, so this should work. You can force it to be TwoWay in the XAML like this:
<Window Title="Window1" Height="300" Width="300">
<Grid>
<StackPanel>
<TextBox Text="{Binding Name, Mode=TwoWay}" Margin="10"/>
<Button HorizontalAlignment="Center"
Content="Click Me" Margin="5"
Padding="2" Click="OnButtonClick" />
</StackPanel>
</Grid>
</Window>
Note the Mode=TwoWay in the Binding declaration.
If that doesn't work, then I suspect that an exception is being thrown in the code that fires the event, or assigns the property and you should look for that.
There seems to be a possibility that you are making the call to change the value on a thread that is not the UI thread. If this is the case, then you either have to marshal the call to fire the property changed event on the UI thread, or make the change to the value on the UI thread.
When an object is bound to a UI element, changes to the object which can affect the UI have to be made on the UI thread.