How to set focus to textbox using MVVM? - c#

How to focus a textbox from ViewModel wpf?
<TextBox Name="PropertySearch"
Text="{Binding UpdateSourceTrigger=PropertyChanged,
Mode=TwoWay, Path=PropertySearch,
ValidatesOnDataErrors=True}"
Width="110"
Height="25"
Margin="10" />

You can do this by adding a property to your ViewModel (or use an existing property) that indicates when the SetFocus should happen but the View should be responsible for actually setting the focus since that is purely View related.
You can do this with a DataTrigger.
View:
<Grid Name="LayoutRoot" DataContext="{StaticResource MyViewModelInstance}">
<Grid.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding UserShouldEditValueNow}" Value="True">
<Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=PropertySearch}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Grid.Style>
<TextBox Name="PropertySearch" Text="{Binding UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, Path=PropertySearch, ValidatesOnDataErrors=True}" Width="110" Height="25" Margin="10" />
</Grid>
ViewModel:
// When you think the view should set focus on a control
this.UserShouldEditValueNow = true;
The example above is simplified by just using a boolean ViewModel property "UserShouldEditValueNow". You can add a property like this to your ViewModel or use some other exising property that indicates this state.
Note: So why is it done this way in MVVM? One reason is, suppose the View author decided to replace the TextBox with a ComboBox, or even better, suppose your property was an integer value that had both a TextBox to view/edit the number and a Slider as another way to edit the same value, both controls bound to the same property... how would the ViewModel know which control to set focus on? (when it shouldn't even know what control, or controls, are bound to it in the first place) This way the View can select which control to focus by changing the ElementName binding target in the DataTrigger Setter.
Happy coding!

The question you should be asking yourself is "why does my ViewModel need to know which control has the focus?"
I'd argue for focus being a view-only property; it's an interaction property, and has nothing to do with the conceptual state. This is akin to the background color of a control: why would you represent it in the VM? If you need to manage the focus in a custom way, it's probably better to use a view-level object to do the job.

In your parent control, add the following property:
FocusManager.FocusedElement="{Binding ElementName=PropertySearch}"

While purists may argue for leaving this out of the VM, there are cases where it may make sense to do so from the VM.
My approach has been to make the view implement an interface, pass that interface to the ViewModel, and then let the VM call methods on the interface.
Example:
public interface IFocusContainer
{
void SetFocus(string target);
}
A couple things to keep in mind:
A VM might serve more than one instance of a view, so your VM might want to have a collection of references to IFocusContainer instances, not just one.
Code the VM defensively. You don't know whether there are 0, 1 or 20 views listening.
The "target" parameter of SetFocus() should probably be "loosely" coupled to the VM. You don't want the VM caring about the exact control names in the UI. Rather, the VM should indicate a name that is defined solely for focus management. In my case, I created some attached properties that would allow me to "tag" controls with "focus names".
To implement the interface, you can:
Implement it in the code-behind
Create some behaviors that know how to attach to the ViewModel that is present in the DataContext.
There's nothing wrong with implementing it on the Code Behind, but the behavior approach does allow a XAML only hookup if that's important to you.
In the implementation of the interface, you can use the visual tree to locate the control, or you could just code up a switch statement for a known set of focusable items.

Related

WPF DependencyProperty updates viewmodel with default value iso new

I am looking at a problem where my own created gauge control doesn't deal with bindings correctly during startup/creation. It works fine once user control and viewmodel are instantiated and all bindings are set.
I have the following control (all user code):
<linearGauge:LinearGaugeControl
Grid.Row="2"
Margin="30, 0, 0, 0"
GaugeLabel="Flow"
LinearGaugeLength="800"
LinearGaugeHeight="80"
LabelFontSize="20"
NeedleColor="Black"
Grid.Column="0" Grid.ColumnSpan="2"
DataContext="{Binding FlowGaugeData}" />
This question is about two properties in the xaml above:
LinearGaugeLength="800"
LinearGaugeHeight="80"
These properties are bound to the view model of the LinearGaugeControl :
<UserControl.Resources>
<Style TargetType="local:LinearGaugeControl">
<Setter Property="LinearGaugeLength" Value="{Binding GaugeSize, Mode=OneWayToSource}"/>
<Setter Property="LinearGaugeHeight" Value="{Binding BarThickness, Mode=OneWayToSource, NotifyOnSourceUpdated=True}"/>
</Style>
</UserControl.Resources>
From my previous struggle with DPs I learned something useful from user ASh, that I can add a callback to my DP so that I at least know that it gets triggered. That works fine. The callback of the LinearGaugeHeight DP fires with the 'new' value of 80 (old value=50).
After that event, my setter gets called, with the wrong value ! (50, the default value of the DP).
What is going wrong?
Is this going wrong because the view is created before the viewmodel is?
In reply to #Clemens:
We are using caliburn, can that in some way cause this problem? I think I read somewhere that caliburn uses DataContext=this under the hoods?

WPF share common property between controls

i've two content controls how can i share a common property between them,
for example if i select some value from combobox in the first content control,
how can the second control know it
<telerikNavigation:RadTabItem Header="1">
<StackPanel>
<ContentControl Content="{Binding EGRPExtractViewModel.View}" />
</StackPanel>
</telerikNavigation:RadTabItem>
<telerikNavigation:RadTabItem Header="2">
<ContentControl Content="{Binding EGRPRightObjectViewModel.View}" />
</telerikNavigation:RadTabItem>
Thanks
You need to use two way binding then respond to the property changing in your ViewModel.
<ContentControl Content="{Binding EGRPRightObjectViewModel.View,Mode=TwoWay}" />
See the MSDN docs for how to respond to changed properties: http://msdn.microsoft.com/en-us/library/ms743695(v=vs.110).aspx
You do not bind view properties. You can bind control properties in same view, so one possibility for you will be to create a control which exposes bindable properties specifically for this reason.
When using mvvm normally view-model should provide all needed properties to the view. If it's a property from another view-model, then it is still have to be provided by view-model of this view (search for questions about how to pass data between view-models to example, here is one).

BindingExpression path errors when switching ViewModels in MVVM application

First things first, some context. If you're familiar with the problem, skip down to the BindingExpression part. This is my first major project in WPF, so I am still quite new to the MVVM pattern. Here is the only other similar question I have found, whose lacklustre answer doesn't really enthuse me much.
I have/am building a .NET 3.5 WPF application and I am using MVVM (implemented myself, no framework). Within this, I have a number of Views and ViewModels. These reside within a master ApplicationView and ApplicationViewModel respectively.
The way I change views is through using XAML DataTemplate elements in the ApplicationView, like so:
<DataTemplate DataType="{x:Type viewmodels:InitViewModel}">
<views:InitView />
</DataTemplate>
And then in the main body I have a ContentControl which binds to a property in ApplicationViewModel
<ContentControl Content="{Binding CurrentPageViewModel}"/>
When I run the application, all of this appears to work fine, and does exactly what is intended. However, when I look at the Debug output after the run, I get a lot of BindingExpression errors.
Here is one for example. I have a property, SplashText, in my InitViewModel. This is bound to a textblock in the splash screen (InitView). When the splash screen ends and I switch out the viewmodel, I get the following:
System.Windows.Data Error: 39 : BindingExpression path error: 'SplashText' property not found on 'object' ''MainMenuViewModel' (HashCode=680171)'. BindingExpression:Path=SplashText; DataItem='MainMenuViewModel' (HashCode=680171); target element is 'TextBox' (Name='FeedBackBox'); target property is 'Text' (type 'String')
I understand that this is because the bindings still exist, but the CurrentPageViewModel property of the DataContext has changed. So what I want to know is:
Is this a fleeting problem, i.e. are the views disposed of when not being used or do they (and the bad bindings) sit there in memory indefinitely?
Is there a way I can clean up or deactivate these bindings while the view is inactive?
What sort of performance knock is it going to have on my application if I leave these alone?
Is there a better way of switching views which avoids this problem?
Thanks in advance, and apologies for the monolithic question.
Edit 03/09/13 - Thanks to Jehof, Francesco De Lisi and Faster Solutions for pointing out that it is pointless to set sub-views datacontext as {Binding DataContext.CurrentPageViewModel, RelativeSource={RelativeSource AncestorType={x:Type Window}}} because the ContentControl takes care of the datacontext.
Your specific example is not reproducible in .NET 4.5, which probably means Microsoft has fixed the problem meantime.
Nevertheless, a similar problem exists when Content and ContentTemplate are both data-bound. I am going to address that problem, which is also likely to solve problems in .NET 3.5 if anyone is still using it. For example:
<ContentControl Content="{Binding Content}" ContentTemplate="{Binding Template}" />
Or when ContentTemplate is determined by DataTrigger:
<ContentControl Content="{Binding Content}">
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<Style.Triggers>
<DataTrigger Binding="{Binding Choice}" Value="1">
<Setter Property="ContentTemplate" Value="{StaticResource TemplateA}" />
</DataTrigger>
<DataTrigger Binding="{Binding Choice}" Value="2">
<Setter Property="ContentTemplate" Value="{StaticResource TemplateB}" />
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
In both cases, one gets binding errors similar to those OP observed.
The trick here is to ensure that changes to Content and ContentTemplate are performed in just the right order to prevent binding errors. I've written DelayedContentControl, which ensures that Content and ContentTemplate are changed at the same time and in the right order.
<jc:DelayedContentControl Content="{Binding Content}" ContentTemplate="{Binding Template}">
Similarly for the DataTrigger case.
You can get DelayedContentControl from my opensource JungleControls library.
It looks like your DataContext goes to MainMenuViewModel while your property belongs to another ViewModel generating the error.
The CurrentPageViewModel value before and after the splash screen changes losing its Binding while switching view.
The problem is dued to DataContext="{Binding DataContext.CurrentPageViewModel, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
In fact, CurrentPageViewModel = InitViewModel when your application starts, but the problem is that every View has the same DataContext (i.e. InitViewModel at first) but I'm sure the ViewModels haven't the entire pool of needed properties to satisfy view bindings.
An example to understand:
ViewX has a binding to PropertyX, managed in ViewModelX.
ViewY has a binding to PropertyY, managed in ViewModelY.
Both have DataContext = CurrentViewModel.
On the startup CurrentViewModel = ViewModelX and both ViewX and ViewY have DataContext = ViewModelX. But this is wrong! And probably will generate an error.
What I usually do is to set in the View class the DataContext (cs or XAML if you prefer) with the corresponding View Model to be sure it fits. Then, when needed, I call a refresh method to update my values every time I switch page. If you have shared properties consider to use a Model to centralize your informations (and values).
A sample image from http://wildermuth.com/images/mvvm_layout.png
Obviously the Views are the Controls wrapped by your MainWindow.
Hope it's clear.
Lets answer your questions in sequence:
You probably already know the answer to this. When .Net garbage collects it'll remove your View object from the heap. But until this time your View object is still bound to the main DataContext on your page and will react to DataContext changed events.
The obvious thing to do is to set the Views DataContext to null. DataContext is a dependency property so the null values scope will just be your View.
As the other/lackluster answer said, it'll slow you down a bit but not a lot. I wouldn't worry too much about this.
Yes. Here's a useful thread on view navigation options: View Navigation Options
I'd also suggest looking at a framework. Something light-weight like MVVM Light will solve a bunch of problems for you with very little integration. It's ViewModelLocator pattern also does what you're doing, but without the side-effects and provides a whole bunch of cleanup options.
You can omit the binding of the DataContext in your Views
DataContext="{Binding DataContext.CurrentPageViewModel, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
cause the DataContext of your View is the DataContext of the ContentControl and that gets set by your binding of the Content-Property.
So, when your property CurrentPageViewModel is set to an InitViewModel the ContentControl will use the InitViewModel as DataContext and use the InitView as ContentTemplate and it will set his own DataContext as DataContext of the InitView.

How to create binding inside custom control automatically?

I have my custom toolbar control with DependencyProperty IsBusy
Here is how I use it:
<Controls:myToolbar
Grid.ColumnSpan="5" Mode="DataEntry"
Status="{Binding State, Converter={StaticResource ViewEditingStateToToolbarStateConverter}}"
IsBusy="{Binding IsBusy}"/>
By convention all my VM's inherit from base VM and have IsBusy property.
So, I KNOW that this property will always be available on VM.
Now I have another 4 properties like this. Instead of adding them to XAML on all my views I want to know how to bind to this IsBusy automatically inside control's code so I don't have to bind in XAML?
EDIT
Actually, I found answer to my question: Silverlight: Programmatically binding control properties
Now, my question is:
Is it correct to apply this binding in constructor like this?
public myToolbar()
{
this.DefaultStyleKey = typeof(myToolbar);
var binding = new Binding("IsBusy") { Mode = BindingMode.TwoWay };
this.SetBinding(IsBusyProperty, binding);
}
Should I check if XAML binding (another binding) exist to this property and not bind? It works either way but I wonder if it's bad for performance, smells, etc?
What about doing this in onApplyTemplate. Is that better way?
if (GetBindingExpression(IsBusyProperty) == null)
{
var binding = new Binding("IsBusy") { Mode = BindingMode.TwoWay };
this.SetBinding(IsBusyProperty, binding);
}
It would be bad if you tried to use this control with a view model which doesn't have the IsBusy property, but even then you'll receive just a debug warning in the output window, nothing to worry about.
As to the place of the binding, the constructor is appropriate if the dependency property which you are binding to doesn't perform any actions inside its callback.
But if the property changed callback tries to call such functions as GetTemplateChild and retrieve inner controls - then you should move the binding to the OnApplyTemplate functions, because only there you can be assured that inner controls exist.
By the way, if your dependency proeprty doesn't have a property changed callback and is used only in the control template like {TemplateBinding IsBusy}, you can replace this line by {Binding IsBusy}. Something like this, either by using binding or data triggers:
<ControlTemplate TargetType="{x:Type Controls:myToolbar}">
<Grid>
<ContentControl x:Name="content" ... />
<ProgressBar x:name="progress" ... />
</Grid>
<ControlTemplate.Triggers>
<DataTrigger Binding="{Binding IsBusy}" Value="True">
<Setter TargetName="progress" Property="Visibility" Value="Visible" />
</DataTrigger>
The idea is simple: TemplateBinding is applied to dependency properties of the control, whereas Binding is applied to properties of the DataContext object or the view model and they can coexist without problems.

WPF: How do I handle an event from a Model to dynamically update xaml in MVVM

I've hit a bit of a dead end in trying to figure this one out... Using the MVVM pattern in WPF, our C# Model fires an event to say something has happened. I want to be able handle that event in my ViewModel and then either kick of a storyboard or change the visibility of a hidden panel on the current Xaml Page. This has to be handled with no Code Behind.
I can sync for the event in my ViewModel, update a property to say what the name of that event is and fire a NotifyPropertyChanged even but how do I get that to either kick off a storyboard or map to a boolean true/false on the Visibility property of my Grid? The property I bind to hs to be the event name as different grids may be shown based on different events so I need a way of mapping this to a boolean. However the ideal solution would be to kick off a storyboard. I've looked at DataTriggers but they all seem to be linked to styles and not to actual pages.
Any ideas of how I can achieve this?
Thanks!
I've used this in the past to kick off a storyboard in code-behind
Storyboard animation = (Storyboard)this.FindResource("ShowPanelStoryboard");
animation.Begin();
This code goes behind the View, not in the ViewModel. Personally, I don't mind some code behind my View providing it is only related the View. In the project I used this in, I added a listener to the VisibilityChanged event and when it got changed to Visible, I ran the storyboard.
As for showing your popup, there's a few ways. One of my favorites was just adding an IsPopupShown property to the ViewModel, binding my panel's visibility to it, and setting it to true anytime the popup should be shown. The ViewModel then handles the events that trigger the popup being shown or not.
An alternative as suggested by Dave White is to use a converter. If your value is not always true/false then you could create a converter that checks if a bound value is equal to the ConverterParameter, and return a Visibility value.
From your comment, it seems to me like what you may want to do is expose an Event property of type object in your view model. When the view model receives an event, it sets Event to an object of a type appropriate for that event. In your XAML, you have this:
<ContentControl Content="{Binding Event}"/>
and in the resource dictionary define a DataTemplate for each specific type of event you want to display. If Event is null, nothing gets displayed. If Event contains an object that you've defined a DataTemplate for, it gets displayed using that template.
Yes, you'll need to create a class for each type of event (if you don't already have one).
Another way is to implement the poor man's template selector:
<TextBlock Text="This is displayed if Foo contains 'BAR'">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Property="Foo" Value="BAR">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
<TextBlock Text="This is displayed if Foo contains 'BAZ'">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Property="Foo" Value="BAZ">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
It's kind of stupidly verbose, but it's an easy way to handling a lot of mutually-exclusive display options.
Bind the Visibility property on your grid, in Xaml, to the boolean property on your ViewModel.
<Grid Visibility="{Binding Path=VisiblePropertyOnViewModel}">
Now do whatever you need in your ViewModel and set the property. As long as it does INotifyPropertyChanged or is a DependencyProperty, it will work.
I'd have to do more digging to figure out how to kick off a Storyboard, but I have no doubt it would be almost as easy. Storyboards can be kicked off by PropertyTriggers as well I believe. I'll leave this to get you started.

Categories