Reputation: 27
I have a ComboBox with items A, B, C, D, E.
How can I change the SelectedValue of a ComboBox after user selection, so if a user select from the list items "A", the SelectedValue will be "D" (as if he selected D himself).
Xaml:
<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>
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;
}
Thanks
Upvotes: 0
Views: 695
Reputation: 150
Add xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
Than you can invoke Command when SelectedItemChanged like
<ComboBox x:Name="NodeCategoriesCombobox">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding UpdateNodeCategoryCommand}" CommandParameter="{Binding ElementName=NodeCategoriesCombobox, Path=SelectedValue}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ComboBox>
Than you add UpdateNodeCategoryCommand and update NodeCategory property
private RelayCommand<string> _updateNodeCategoryCommand ;
public RelayCommand<string> UpdateNodeCategoryCommand {
get { return _updateNodeCategoryCommand ?? (_updateNodeCategoryCommand = new RelayCommand<string>( nodeCategory => { NodeCategory=nodeCategory }));
}
}
Upvotes: 2