Combobox selectedindex = -1 также удаляет текст, написанный в редактируемом комбинированном списке - PullRequest
0 голосов
/ 28 апреля 2018

Проблема в том, что когда я делаю selectedindex = -1, он удаляет текст, записанный в выпадающем списке. Я только хочу отменить выбор элемента в раскрывающемся списке, но текст должен оставаться написанным в текстовой области comboxbox.

Я также пытался использовать selecteditem = null, но он также ведет себя так же. Я добавляю свой проект ниже.

Я использую проверку ввода и ввод ключевой команды, поэтому все результаты учитываются после нажатия клавиши ввода.

Пожалуйста, дайте мне знать, если потребуется более подробная информация.

ViewModel

public class ViewModel : ValidateObservableObject
{
    public ViewModel()
    {
        this.ErrorsChanged += RaiseCanExecuteChanged;
    }

    private void RaiseCanExecuteChanged(object sender, DataErrorsChangedEventArgs e)
    {
        if (this.HasErrors)
        {
            ItemSelected = -1;  //It also deletes the text written in the combobox
        }

        else
        {
            Locations.Add(Location);
            SelectedLocation = Location;

        }
    }

    private int _itemSelected;

    public int ItemSelected
    {
        get => _itemSelected;
        set
        {
            _itemSelected = value;
            OnPropertyChanged("ItemSelected");
        }
    }

    private RelayCommand _comboBoxEnterKeyCommand;

    public RelayCommand ComboxBoxEnterKeyCommand => _comboBoxEnterKeyCommand ?? (_comboBoxEnterKeyCommand = new RelayCommand(EnterPress));

    private void EnterPress(object obj)
    {
        Location = (string) obj;


    }

    private ObservableCollection<string> _locations;

    public ObservableCollection<string> Locations
    {
        get { return _locations ?? (_locations = new ObservableCollection<string>()); }
        set
        {
            _locations = value;
            OnPropertyChanged(nameof(Locations));
        }
    }


    private string _location;

    [RegularExpression("^[a-zA-Z0-9 ]*$", ErrorMessage = "Special characters not allowed")]
    public string Location
    {
        get { return _location; }
        set
        {
            SetProperty(ref _location, value);
        }
    }

    private string _selectedLocation;

    public string SelectedLocation
    {
        get { return _selectedLocation; }
        set
        {
            _selectedLocation = value;
            OnPropertyChanged(nameof(SelectedLocation));
        }
    }
}

View

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <ComboBox Margin="10" x:Name="Combobox" IsEditable="True" SelectedIndex="{Binding Path = ItemSelected}" ItemsSource="{Binding Locations}">
        <ComboBox.InputBindings>
            <KeyBinding Command="{Binding ComboxBoxEnterKeyCommand}" CommandParameter="{Binding ElementName=Combobox,Path=Text}" Key="Enter"/>
        </ComboBox.InputBindings>
        <ComboBox.Text>
            <Binding Path="Location" UpdateSourceTrigger="LostFocus" ValidatesOnNotifyDataErrors="True" Mode="TwoWay" />
        </ComboBox.Text>
        <ComboBox.VerticalContentAlignment>Center</ComboBox.VerticalContentAlignment>
        <ComboBox.IsTextSearchEnabled>False</ComboBox.IsTextSearchEnabled>
        <ComboBox.SelectedItem>
            <Binding Path="SelectedLocation" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged"  />
        </ComboBox.SelectedItem>
    </ComboBox>
</Grid>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...