代码:
private ObservableCollection<State> allStates = new ObservableCollection<State>();
// State是一个包含许多属性的类,其中一个是int&#39; Index&#39;和int&#39; OneArrow&#39;
public MainWindow()
{
...
this.MyComboBox.ItemsSource = allStates;
this.MyComboBox.DisplayMemberPath = "Index";
this.MyComboBox.SelectedValuePath = "Index";
this.DataContext = MyState;
}
xaml中的:
<ComboBox Name="MyComboBox"
Width="60" Height="20"
IsEnabled="False"
SelectedValue="{Binding Path=OneArrow, UpdateSourceTrigger=PropertyChanged}"/>
绑定工作正常,很好,但我有另一个问题。 Combobox不会选择所选项目。我的意思是在下拉列表中突出显示正确的项目,但是当隐藏下拉列表时,不会显示任何内容。
答案 0 :(得分:0)
没有看到你所有的课程,很难猜到什么是错的。 这是我对你的代码的看法。
的Xaml:
<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)