How to get the selected name,value from WPFAutoComplete:TextBoxAutoCompleteProvider event? - wpf

I am new to XAML forms. I have some code written years ago by another programmer which I now need to modify. I am trying to intercept the selection that is applied to the textbox when the user presses enter or clicks the mouse on a selection from the dropdown list.
<TextBox x:Name="txtVendor" HorizontalAlignment="Left" Height="23" Margin="24,299,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="250"/>
<WPFAutoComplete:TextBoxAutoCompleteProvider x:Name="txtVendorAuto" DisplayMemberPath="Name" SelectedValuePath="VendorNumber" HorizontalAlignment="Left" Height="100" Margin="24,322,0,0" VerticalAlignment="Top" Width="250" TargetControl="{Binding ElementName=txtVendor}" MaxResults="20" MinWidth="250" MinTypedCharacters="2"/>
I thought it would be similar to C#/Vb code in that I would check the selected index change event and get the values, however the only event that looks close is the "SelectionChanged" which fires with any text input and not the actual selected item. I managed to check for the keydown event in the textbox and look for the enter key and that seems to work, but I cannot determine when someone has selected something via the mouse. I have checked the various mouse events (left mouse button down,up, etc.)
Is there a way to simply get the item from the search when it is selected (keyboard or mouse)?

Related

Combobox: Get text and selected item in mvvm way

The combobox is editable so user can also write. I have two usecases:
Get the text from combobox in a Lostfocus way, when user writes
something in the box and when he presses "Tab" then I want the text
from the combobox and I add the value in the itemsSource list.
When the users makes the selection from the combobox dropdown, I want that
selected item as soon he selects it and this time I dont
want to have it in Lostfocus manner but somewhat like
PropertyChanged way.
I tried the code which is given below:
<ComboBox Margin="3" x:Name="Combobox" SelectedItem="{Binding SelectedPath, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Text="{Binding PathLocation, UpdateSourceTrigger=LostFocus, ValidatesOnNotifyDataErrors=True}" IsTextSearchEnabled="True" VerticalContentAlignment="Center" ItemsSource="{Binding SelectedPaths}" IsEditable="True" Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="2" HorizontalAlignment="Stretch"/>
Things worked fine for the first time when the application starts but after some interactions the problem arises. When the user starts typing in the combobox the SelectedItem property of combobox triggers which is contrary to what I want in the first use case.
In short: when the user writes something in the combobox I want to have it in a Lostfocus manner and when he makes the selection from the dropdown of combobox I want to have it in a PropertyChanged manner.
Let me know if more details are required.
I removed the "IsTextSearchEnabled" property but it also didnt work then I came to know that "IsTextSearchEnabled" property of Comobobox is by default true, which is causing some values suggested by the combobox are setting in my properties. As soon as I made the "IsTextSearchEnabled" to false, it is working fine.

Embedded ComboBox in Button, but Button steals click event when activating drop down

I have an application with limited screen space, so I'm trying to conserve some real estate by putting a combo box within a button. Its pretty nifty and it looks exactly like what I wanted it to look like. The problem is, every time I click the down arrow on the combo box, the Button also receives a click event. The drop down menu still works properly, but my button has already fired before I've had a chance to actually select what I wanted.
Here is my WPF code that describes my Button and its contents.
<Button FontSize="14" Height="32" HorizontalAlignment="Left" Click="DisableCopierButton_Click">
<StackPanel Orientation="Horizontal">
<Label Content="Disable Copier:" />
<ComboBox Name="DisableCopierComboBox">
<ComboBoxItem Content="1"/>
<ComboBoxItem Content="2"/>
</ComboBox>
</StackPanel>
</Button>
My question is, when I'm clicking on the ComboBox and only the ComboBox, how do I prevent the click event from passing through the button that is underneath it?
I finally found it. I went with the solution provided by Rachel here, even though it was not selected as the answer.
private void EnableCopierButton_Click(object sender, RoutedEventArgs e)
{
if (!(e.OriginalSource is Button))
{
// combo box was clicked, not the button, so get out of here.
return;
}
}
This seems like a SplitButton, yeah. Don't reinvent the wheel. Plenty of implementations on the web.
I recommend WPF Toolkit Extended's.
Rather than making the combo box be part of the button's Content, you may want to try creating a ContentTemplate for the button that includes a combo box.

AutoCompleteBox with TextChanged event not selecting properly

Hi I'm using an AutoCompleteBox like this
<!-- XAML Code -->
<sdk:AutoCompleteBox Grid.Row="2"
FilterMode="None"
ItemsSource="{Binding Customers}"
SelectedItem="{Binding Path=SelectedCustomer, Mode=TwoWay}"
Text="{Binding CustomerSearchString, Mode=TwoWay}"
ValueMemberBinding="{Binding Path=FullName}"
ValueMemberPath="FullName"
TextChanged="{ext:Invoke MethodName=Search, Source={Binding}}"/>
C# part:
// Search Method in the viewmodel
public void Search()
{
var customerOperation = _context.Load(_context.GetCustomerByNameQuery(CustomerSearchString));
customerOperation.Completed += (s, e) => Customers = new List<Customer>(customerOperation.Entities);
}
In my app to quick-search for customers for an fast and uncomplicated method to search. I get it to display everything correctly in the dropdown, and when I select with the mouse it works perfectly.
But when I press ArrowDown, you see the text come up for a split-second but then it reverts and puts the cursor back in the textbox instead of selecting the first entry down. I tried using the TextInput event, but that one won't fire.
How can I avoid this behaviour?
SOLUTION:
The problem was, that the TextChanged event got fired when the user selected an entry, creating some sort of race condition like behaviour where the Text got reset. The solution was to use the KeyUp event (don't use KeyDown, because the Text property won't be updated yet). This event doesn't get triggered when the user selects something, solving the problem.
Final code (ViewModel unchanged):
<!-- XAML Code -->
<sdk:AutoCompleteBox Grid.Row="2"
FilterMode="None"
ItemsSource="{Binding Customers}"
SelectedItem="{Binding Path=SelectedCustomer, Mode=TwoWay}"
Text="{Binding CustomerSearchString, Mode=TwoWay}"
ValueMemberBinding="{Binding Path=FullName}"
ValueMemberPath="FullName"
KeyUp="{ext:Invoke MethodName=Search, Source={Binding}}"/>
Thanks everyone!
Add a handler like this in code:
KeyEventHandler eventHandler = MyAutoCompleteBox_KeyDown;
MyAutoCompleteBox.AddHandler(KeyDownEvent, eventHandler, true);
I'm not understanding why you are using a TextChanged event...? What is that for? If you take that out, does it work? I use an autocomplete box in my project and I don't need a search method... all I do is just supply a list of objects to the autocompletebox and the it searches that list when the user types. I can select either by mouse or by up/down arrows. The only thing that I can think of is that each time you try to use the up/down arrow the text changes and fires off the search function and closes the selection option drop down...

WPF Unleashed error?

The book says
The WPF Button class only adds two
simple concepts on top of what
ButtonBase already provides: being a
cancel button or a default button.
These two mechanisms are handy short-
cuts for dialogs. If Button.IsCancel
is setto true on a Button inside a
dialog (that is, a Window shown via
its ShowDialog method), the Window is
automatically closed with a
DialogResult of false. If
Button.IsDefault is set to true,
pressing Enter causes the Button to be
clicked unless focus is explicitly
taken away from it.
But in this sample window
<Window xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Title="About WPF Unleashed" SizeToContent="WidthAndHeight"
Background="OrangeRed" >
<StackPanel>
<Label FontWeight="Bold" FontSize="20" Foreground="White">
WPF Unleashed (Version 3.0)
</Label>
<Label> 2006 SAMS Publishing</Label>
<Label>Installed Chapters:</Label>
<ListBox>
<ListBoxItem>Chapter 1</ListBoxItem>
<ListBoxItem>Chapter 2</ListBoxItem>
</ListBox>
<TextBox AcceptsReturn="False">HELLO TEXT</TextBox>
<RadioButton>HELLO RADIO BUTTON</RadioButton>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<Button IsCancel="True" MinWidth="75" Margin="10">Cancel</Button>
<Button x:Name="OKBUTTON" IsDefault="True" MinWidth="75" Margin="10">OK</Button>
</StackPanel>
<StatusBar>You have successfully registered this product.</StatusBar>
</StackPanel>
</Window>
If I press Enter or even click it, the modal Window(By ShowDialog()) does not get closed (leave aside the return value).
Is that an error in the book ?
I believe it is an error. IsDefault and IsCancel simply means that some access-key-magic is applied when the window is created, so that the button is clicked when you hit 'Enter' and 'ESC' respectively.
If you want a Window to close - you need to:
(from MSDN )
When a dialog box is accepted, it should return a dialog box result of true, which is achieved by setting the DialogResult property when the OK button is clicked
...
Note that setting the DialogResult property also causes the window to close automatically, which alleviates the need to explicitly call Close.

Triggering data validation in WPF

I have a problem in WPF with validation.
I have a user control which has few textboxes, which are binding to datamodel.
The validation is implemented with IDataErrorInfo.
I want the validation to be triggered only when the user press the button "Submit data", so I used UpdateSourceTrigger="Explicit" with the binding of all those text boxes.
Everything working fine, and the validation only triggered when the user push the button, where I update the datasources.
But that user control can be hidden or shown, and when I changed the visibility from display/ to hidden and then back to display, the validation is triggered.
Is there a way to control the validation on that stage?
This is the code that I am using
The binding to the textbox
<TextBox
AutomationProperties.AutomationId="StreetNameTextBoxId"
Height="20" Margin="0,0,5,0" FontSize="12" Name="_streetNameText"
AcceptsReturn="False" AcceptsTab="False" Focusable="True"
Text="{Binding ElementName=_this, Path=SearchParameters.EnteredAddress, UpdateSourceTrigger=Explicit}">
The code that is executing the validation and search (which is associated to click of a button called "Search")
private void ExecuteSearch() {
_streetNameText.UpdateDataSource();
if (ViewModel.CustomerSpecification.IsValid())
PerformActionInBackground(delegate{PerformSearch();});
}

Resources