1

在代码中:

private ObservableCollection<State> allStates = new ObservableCollection<State>();

//State 是一个有很多属性的类,其中一个是 int 'Index' 和 int 'OneArrow'

public MainWindow()
{
...

this.MyComboBox.ItemsSource = allStates;
this.MyComboBox.DisplayMemberPath = "Index";
this.MyComboBox.SelectedValuePath = "Index";

this.DataContext = MyState;
}

在xml中:

<ComboBox Name="MyComboBox" 
Width="60" Height="20" 
IsEnabled="False" 
SelectedValue="{Binding Path=OneArrow, UpdateSourceTrigger=PropertyChanged}"/>

绑定工作正常,很好,但我还有另一个问题。组合框不显示所选项目。我的意思是在下拉列表中突出显示正确的项目,但是当隐藏下拉列表时,什么都不会显示。

在此处输入图像描述

4

1 回答 1

0

如果没有看到你所有的课程,很难猜测出了什么问题。这是我对您的代码外观的解释。

xml:

<Window x:Class="WpfApplication4.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" Name="UI">
    <Grid >
        <ComboBox ItemsSource="{Binding ElementName=UI, Path=AllStates}" 
                  DisplayMemberPath="Index"
                  SelectedValuePath="Index"
                  SelectedValue="{Binding ElementName=UI, Path=OneArrow}"
                  Height="21" HorizontalAlignment="Left" Margin="80,82,0,0" Name="comboBox1" VerticalAlignment="Top" Width="152" />
    </Grid>
</Window>

代码背后:

 /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            AllStates.Add(new State { Index = 1 });
            AllStates.Add(new State { Index = 2 });
            AllStates.Add(new State { Index = 3 });
            AllStates.Add(new State { Index = 4 });
        }

        private ObservableCollection<State> allStates = new ObservableCollection<State>();
        public ObservableCollection<State> AllStates 
        {
            get { return allStates; }
            set { allStates = value; }
        }

        private int oneArrow;
        public int OneArrow
        {
            get { return oneArrow; }
            set { oneArrow = value; }
        }

    }

    public class State : INotifyPropertyChanged
    {
        private int index;
        public int Index
        {
            get { return index; }
            set { index = value; NotifyPropertyChanged("Index"); }
        }


        public event PropertyChangedEventHandler PropertyChanged;
        public void NotifyPropertyChanged(string property)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(property));
            }
        }
    }

这似乎工作正常,但就像我说的那样,我不知道你的 State 类是什么样子或者 OneArrow 位于哪里(mainform 或 State)

于 2012-11-26T22:30:55.580 回答