Mike
Mike

Reputation: 3284

Updating Value from Setter Not Refreshed in the Control

I have a dropdown which has 3 items inside it. What I'm trying to do is if I select a particular item, I need to evaluate a rule, and if the rule suggests a different item to be selected, I need to select that instead of what user has selected.

For instance I have 3 items "ABC", "DEF" & "GHI". If user tries to select "ABC" then I need to select "DEF". I'm doing this from the setter of selected item property but for some weird reason it does't update. I knew a similar issue exsisted in .NET 3.5 and was resolved in .NET 4.0, but I'm using .NET 4.0 and in my case it still persists. Please can you suggest how to resolve this issue?

Code:

ViewModel:

     public class ViewModel
        {
           public ViewModel()
           {
            AllItems = new List<string> { "ABC", "DEF", "GHI" };
           }

           private List<string> _itemsList;
            public List<string> AllItems
            {
                get { return _itemsList; }
                set
                {
                    _itemsList = value;
                    OnPropertyChanged("AllItems");
                }
            }

            private string _selectedItem;
            public string SelectedItem
            {
                get { return _selectedItem; }

                set
                {
                    _selectedItem = ValidateRules(value);
                    OnPropertyChanged("SelectedItem");
                }
            }

            public string ValidateRules(string selection)
            {
                if (selection == "ABC")
                    return "DEF";

                return selection;
            }
        }

View:

 <Grid>
        <ComboBox ItemsSource="{Binding AllItems}" SelectedItem="{Binding SelectedItem, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Center" VerticalAlignment="Center" Width="200"/>
    </Grid>

Upvotes: 0

Views: 88

Answers (1)

Dineshreddybandi
Dineshreddybandi

Reputation: 135

Change the UpdateSourceTrigger to LostFocus rather than PropertyChanged. It will work.

  <ComboBox ItemsSource="{Binding AllItems}" SelectedItem="{Binding SelectedItem, UpdateSourceTrigger=LostFocus}" HorizontalAlignment="Center" VerticalAlignment="Center" Width="200"/>

it will work.

Mark it answered if it solves your question.

Upvotes: 1

Related Questions