WPF Activate binding OnTextInput on textbox - c#

I have a textbox with the following binding :
<TextBox Binding={Path=MyStr, Mode=TwoWay}>
My problem is that the binding only fires when the textbox loses focus and not for each char the user enters.
The textbox also has an OnTextInput function that fires properly but how do I activate the binding in the code behind?
*I'd rather doing it in a pure mvvm way (not use the window's code behind if possible)
Any answer will be accepted mvvm or not.

Here:
<TextBox Text="{Binding Path=MyStr, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
now your bound property will be changed on each character.

U can use the updatesource trigger and set it to property changed
<Binding Source="{StaticResource myDataSource}" Path="Name"
UpdateSourceTrigger="PropertyChanged"/>
The moment it is changed it will sent it's updated value back to your DataContext
on msdn:
http://msdn.microsoft.com/en-us/library/system.windows.data.updatesourcetrigger.aspx

There is a UpdateSourceTrigger Called PropertyChanged, if you use that as your update trigger when you change the text of the textbox it will fire and in your binding property setter you can perform what ever action you need to happen as text changes.
<TextBox Text="{Binding Path=Text,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" />

Related

Is it possible in WPF to bind a property to two properties?

I'm developing a C#/WPF MVVM application and I have the following controls in my Xaml:
<TextBox Text="{Binding ElementName=PriceSlider, Path=Value, Mode=TwoWay}"/>
<Slider x:Name="PriceSlider" Minimum="0" Maximum="10000"/>
The user should be able to set the textbox's value both by typing it in and through the slider indirectly, so I need this binding between them. Moreover, I should bind the textbox's value into one of my VM's property for validation and further computation.
I thought about using the textbox's TextChanged event with the CallMethodAction of the Xaml.Behaviours package passing the EventArgs, but I guess it wouldn't be so efficient to fire events every time the slider sends a new value.
Is there a way to bind the textbox both to the slider and e.g. OneWayToSource to one of the DataContext's property? Or any other way that is sort of efficient?

WPF - TextBox not binding properly when set to readonly

I have TextBox that I'm using to add (only to add and not read) file path into DB. Text property is set when user selects certain file (OpenFileDialog). So, I set it in readonly state and it won't bind properly. When I remove readonly it works fine.
<Button Name="btnAddFile" Content="+" HorizontalAlignment="Left" Width="23" Height="23" Click="AddFilePath"/>
<TextBox Name="tbxFilePath" Height="23" Text="{Binding FilePath}" Width="364" IsReadOnly="True"/>
When I use:
Text="{Binding FilePath, Mode=OneWayToSource}"
it sometimes work but most of the time it doesn't (?!). I could use TextBlock or Label but I would really like to understand what is going on and use TextBox.
I'm using Entity Framework but don't think it does matter.
Question: How can I programmatically add text to TextBox control which is readonly and be able to bind it.
EDIT: I figured out what the problem is. When I set focus on TextBox after I set it's Text property from code-behind, it works. I guess it has to notify that Text is changed when I do it from code-behind. How to do that?
Have you tried using OneWay Binding?
MSDN reads:
OneWay Updates the binding target (target) property when the binding source (source) changes. This type of binding is appropriate if the control being bound is implicitly read-only.
Which I think covers your scenario.
The target is your TextBox Text property and your source is your FilePath property on your ViewModel.
Use:
Text="{Binding FilePath, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
EDIT
This answer assumes you have implemented INotifyPropertyChanged on your ViewModel.
EDIT
The correct binding mode is OneWayToSource. Confirmed by OP.

How to control when TextBox Text as binding source updates the target value?

Trying for a simple thing. I want TextBlock text to be updated to what TextBox's text value is. However, I want it to happen only on LostFocus. Currently below code updates a TextBlock as user is typing into a TextBox. How do we achieve that?
<StackPanel>
<TextBox x:Name="txtQty" />
<TextBlock Text="{Binding ElementName=txtQty, Path=Text}" />
</StackPanel>
I explored the UpdateSourceTrigger property on textbox with LostFocus, but it won't work as that controls how the source should be updated, whereas here I need how the destination updates.
I prefer to have a XAML only solution.
XAML is a markup language.
The straight-forward way to to this would be to bind the TextBox and the TextBlock to the same view model source property. The source property will be set when the TextBox loses focus and then the TextBlock will then be updated provided that the view model class implements the INotifyPropertyChanged interface as expected.
You could of course also handle the LostKeyboardFocus event for the TextBox and set the Text property of the TextBlock programmatically in the code-behind of the view. This approach is not any worse than trying to implement some logic in the XAML markup of the very same view. Just because you possibly can do something in pure XAML, it doesn't mean that you always should. A programming language such as C# usually does a better job implementing some logic.
As others already said, the best way would be to bind the TextBlock and the TextBox to the same viewmodel property.
If you want to do it only with XAML code you could try it from the other side and bind your TextBox to the TextBlock.
Like this:
<StackPanel>
<TextBox Text="{Binding ElementName=txtQty, Path=Text, UpdateSourceTrigger=LostFocus, Mode=OneWayToSource}" />
<TextBlock x:Name="txtQty" />
</StackPanel>

WPF validation without updating the data source

I have a TextBox displaying the time part of a DateTime:
<TextBox HorizontalAlignment="Left" Height="23" Margin="0,13,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" Validation.Error="Validation_OnError">
<TextBox.Text>
<Binding Path="MyDate" StringFormat="HH:mm" NotifyOnValidationError="True" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<c:TimeValidator></c:TimeValidator>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
Is it possible to do the validation on property change, and the conversion on lost focus?
I want to have the validation on property changed, but I want to have my data source updated on lost focus. Otherwise, the converter will kick in while the user is editing in the TextBox. This might be a problem if the values is 10:50 and the user deletes the last number, so that the value becomes 10:5. The converter will then convert this to 10:50. This is okay to do on lost focus, but not on property changed. But for the sake of the validator, i want to validate on property change so the user have the red border as long as the entered value is not valid.
Yes! I was just wrestling with this. AFAIK, there is no XAML combination for this--it must be done in the codebehind, and you need a direct reference to the element.
Element.GetBindingExpression(PropertyName).ValidateWithoutUpdate();
You'll probably want to check that GetBindingExpression doesn't return null; this will run any converters you have attached (presumably to supply the converted value to converters with ValidationStep set to ConvertedProposedValue), but will not update the source. And, of course, you'll have to call this in some event, perhaps TextChanged or somesuch. Here is the MSDN documentation for it: https://msdn.microsoft.com/en-us/library/system.windows.data.bindingexpressionbase.validatewithoutupdate(v=vs.110).aspx
Use this code:
BindingExpression expression =
txtStudentName.GetBindingExpression(TextBox.TextProperty);
expression.ValidateWithoutUpdate();
If you want to update it's source after check use this code:
BindingExpression expression =
txtStudentName.GetBindingExpression(TextBox.TextProperty);
expression.ValidateWithoutUpdate();
if (expression!=null && !expression.HasError)
expression.UpdateSource();

Mvvm wpf: update value binding before leaving focus of input element

I have this element in my xaml (DevExpress item):
<dxe:ComboBoxEdit IsTextEditable="False" EditValue="{Binding IDTIPOCONN}"
ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Window},Path=DataContext.ttc}" />
All the binding are correct, and when I change the value, I trigger some event from my ViewModel.
My problem is the update of the value is executed only when I leave the focus of my comboBox. I need, instead, to execute my action when the value is changed, before leaving its foucs.
How can I do it? I need this because selecting one or another from the list, I show to the user some hidden elements.
Try for Binding set UpdateSourceTrigger=PropertyChanged:
<dxe:ComboBoxEdit IsTextEditable="False"
EditValue="{Binding Path=IDTIPOCONN, UpdateSourceTrigger=PropertyChanged}" ... />
In this case, most likely the default value of UpdateSourceTrigger is LostFocus.

Categories

Resources