如何在组合框中设置选定的项目

问题描述 投票:11回答:2

似乎没有人找到一种方法来将组合框设置为SelectedItem =“Binding Property”。

解决方案是在组合框项目源中的ViewModel对象中使用IsSelected属性吗?

wpf mvvm combobox set selecteditem
2个回答
15
投票

我们成功绑定组合框的方法如下......

<ComboBox 
    ItemsSource="{Binding Path=AllItems}" 
    SelectedItem="{Binding Path=CurrentItem, Mode=TwoWay}" />
<TextBlock Text="{Binding Path=CurrentItem, Mode=TwoWay}" />

class public ItemListViewModel
{
    public ObservableCollection<Item> AllItems {get; set;}

    private Item _currentItem;
    public Item CurrentItem
    {
        get { return _currentItem; }
        set
        {
            if (_currentItem == value) return;
            _currentItem = value;
            RaisePropertyChanged("CurrentItem");
        }
    }
}

5
投票

不知道为什么你不能在没有看到代码的情况下将数据绑定到ComboBox上的SelectedItem。下面将向您展示如何使用CollectionView进行操作,该ViewView具有组合框支持的当前项目管理。 CollectionView有一个CurrentItem get属性,可用于获取当前选中的属性。

XAML:

<Window x:Class="CBTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <StackPanel>
        <ComboBox 
            ItemsSource="{Binding Path=Names}"
            IsSynchronizedWithCurrentItem="True">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding}" />
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>
        <TextBlock Text="{Binding Path=Names.CurrentItem}" />
    </StackPanel>
</Window>

代码背后:

using System.Collections.Generic;
using System.Windows;
using System.Windows.Data;

namespace CBTest
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            DataContext = new VM();
        }
    }

    public class VM
    {
        public VM()
        {
            _namesModel.Add("Bob");
            _namesModel.Add("Joe"); 
            _namesModel.Add("Sally"); 
            _namesModel.Add("Lucy");

            Names = new CollectionView(_namesModel);

            // Set currently selected item to Sally.

            Names.MoveCurrentTo("Sally");
        }

        public CollectionView Names { get; private set; }

        private List<string> _namesModel = new List<string>();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.