组合框选定的项目已更新为模型属性

时间:2020-04-10 10:34:22

标签: wpf xaml data-binding combobox

将模型属性的设置属性绑定到选定属性后绑定到所选项目的组合框的模型属性不会更新回模型属性。例如:在我们的方案中,我们会动态更新商品来源和所选商品。在这里,我们将所选项目设置为null,然后处理null并回滚到组合框的第一项。该视图已正确更新,但模型仍仅保留null。请找到以下代码以供参考。

public class ViewModel : BaseViewModel
{
    ObservableCollection<string> Xitems;
    string Xselected;

    public ObservableCollection<string> XItems
    {
        get
        {
            return Xitems;
        }
        set
        {
            Xitems = value;
            NotifyPropertyChanged();
        }
    }
    public string XSelected
    {
        get
        {
            return Xselected;
        }
        set
        {
            Xselected = value;
            NotifyPropertyChanged();
        }
    }
    ObservableCollection<string> Yitems;
    string Yselected;

    public ObservableCollection<string> YItems
    {
        get
        {
            return Yitems;
        }
        set
        {
            Yitems = value;
            NotifyPropertyChanged();
        }
    }
    public string YSelected
    {
        get
        {
            return Yselected;
        }
        set
        {
            Yselected = value;
            NotifyPropertyChanged();
        }
    }
    public bool isModified { get; set; }
}
public partial class MainWindow : Window
{
    ViewModel viewModel = new ViewModel();
    static MainWindow()
    {

    }
    public MainWindow()
    {
        DataContext = viewModel;
        viewModel.XItems = new ObservableCollection<string> { "Thadam", "Comali", "Kaithi", "Thuppakki", "Kaththi" };
        viewModel.XSelected = "Kaththi";
        viewModel.YItems = new ObservableCollection<string>() { "B", "A", "C" };
        viewModel.YSelected = "A";
        InitializeComponent();
    }

    private void ComboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if((sender as ComboBox).IsKeyboardFocusWithin)
        {
            viewModel.isModified = false;
            viewModel.YItems = new ObservableCollection<string>() { "Banana", "Apple", "Ice" };
            viewModel.YSelected = "Apple";
            viewModel.isModified = true;
            viewModel.YSelected = null;

        }
    }
    private void ComboBox2_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (viewModel.isModified)
        {
            (sender as ComboBox).SelectedIndex = 0;
            MessageBox.Show(viewModel.YSelected);
        }
    }
}

xaml

 <StackPanel>
        <ComboBox ItemsSource="{Binding XItems}" SelectedItem="{Binding XSelected}"  SelectionChanged="ComboBox1_SelectionChanged"></ComboBox>

        <ComboBox ItemsSource="{Binding YItems}" SelectedItem="{Binding YSelected,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectionChanged="ComboBox2_SelectionChanged"></ComboBox>
    </StackPanel>

请注意,消息框仍仅显示空值。

0 个答案:

没有答案