In my MVVM app I have a textbox and a combobox.
User write a numeric value in the textbox and the combobox dropdown (upon textbox input) and user select a level from the combobox (he cannot open the combobox by himself).
I want to check both inputs and change the combobox accordingly.
For example if user set the textbox to 1200.5 mV I would change the textbox to 1.0 and the combobox to V.
Question 1:
How can I change the combobox SelectedValue programmatically so the user could see the new value?
Question 2:
How can I dropdown the combobox but still keep the focus on the textbox (even if my mouse cursor is on the combobox dropdown)? It seems that I lose focus on the textbox after the first selection from the combobox .
Thanks.
XAML:
<Grid >
<StackPanel Orientation="Horizontal">
<TextBox Text="{Binding Path=Name, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" Height="25" Width="100"
/>
<ComboBox
IsDropDownOpen="{Binding IsDropDownOpen, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
ItemsSource="{Binding OffsetValues}"
SelectedValue="{Binding NodeCategory, Mode=TwoWay}"
Height="25" Width="100" IsHitTestVisible="False" Background="AliceBlue">
<ComboBox.Resources>
<sys:Double x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}">0</sys:Double>
</ComboBox.Resources>
</ComboBox>
</StackPanel>
</Grid>
ViewModel:
class ViewModel : ViewModelBase
{
private IList<string> offsetValues = new List<string>() { "mV", "V" };
public IList<string> OffsetValues
{
get
{
return offsetValues;
}
set
{
offsetValues = value;
}
}
private bool isDropDownOpen;
public bool IsDropDownOpen
{
get { return isDropDownOpen; }
set
{
isDropDownOpen = value;
OnPropertyChanged();
}
}
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged( "Name" );
if( _name != "" )
{
isDropDownOpen = true;
OnPropertyChanged( "IsDropDownOpen" );
}
}
}
private string _NodeCategory;
public string NodeCategory
{
get
{
return _NodeCategory;
}
set
{
if( Convert.ToDouble( _name ) > 1000 )
{
_name = "1.0";
OnPropertyChanged( "Name" );
_NodeCategory = OffsetValues[1];
OnPropertyChanged( "NodeCategory" );
}
else
{
_NodeCategory = value;
OnPropertyChanged( "NodeCategory" );
}
}
}
}
public class ViewModelBase : INotifyPropertyChanged
{
protected virtual void OnPropertyChanged( [CallerMemberName]string propertyName = null )
{
PropertyChanged.Invoke( this, new PropertyChangedEventArgs( propertyName ) );
}
public event PropertyChangedEventHandler PropertyChanged;
}