【发布时间】:2017-08-17 18:14:56
【问题描述】:
我想扩展我之前的问题 Pass ComboBox Selected Item as Method Parameter
回复https://stackoverflow.com/a/45703484/6806643
我有一个绑定到项目列表的组合框。
我想在按下按钮时将 ComboBox 更改为不同的项目列表。
发件人:Red, Orange Yellow, Green, Blue, Purple
收件人:Cyan, Magenta, Yellow, Black
程序启动时设置的项目。在Change Button 中,我将新颜色添加到_myComboItems 列表中,但是如何在按下按钮时重新设置?
XAML
<Window x:Class="MyProgram.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MyProgram"
mc:Ignorable="d"
Title="MainWindow" Height="289" Width="525">
<Grid>
<ComboBox x:Name="comboBox"
DisplayMemberPath="Name"
ItemsSource="{Binding MyComboItems}"
SelectedItem="{Binding SelectedComboItem}"
SelectedIndex="0"
HorizontalAlignment="Left"
Margin="264,88,0,0"
VerticalAlignment="Top"
Width="120"/>
<Button x:Name="buttonChange"
Content="Change"
HorizontalAlignment="Left"
Margin="142,88,0,0"
VerticalAlignment="Top"
Width="75"
Click="button1_Click"/>
</Grid>
</Window>
C#
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = this;
SelectedComboItem = MyComboItems[0];
}
// ComboBox Items
//
private List<ComboItem> _myComboItems = new List<ComboItem>()
{
new ComboItem("Red"),
new ComboItem("Orange"),
new ComboItem("Yellow"),
new ComboItem("Green"),
new ComboItem("Blue"),
new ComboItem("Purple")
};
public List<ComboItem> MyComboItems
{
get { return _myComboItems; }
}
// Property Changed
//
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
// Selected Item
//
private ComboItem _selected = null;
public ComboItem SelectedComboItem
{
get { return _selected; }
set
{
_selected = value;
OnPropertyChanged("SelectedComboItem");
}
}
// Change ComboBox Items
//
private void buttonChange_Click(object sender, RoutedEventArgs e)
{
// Change Items Here
}
}
public class ComboItem
{
public string Name { get; private set; }
public ComboItem(string color)
{
Name = color;
}
}
【问题讨论】:
-
您通常应该将 MVVM 与 WPF 一起使用。这种东西在那里变得非常容易。
-
请注意,没有必要将 ItemsSource 绑定到 ComboBoxItems 的集合。您也可以简单地使用字符串集合。将为幕后的每个项目自动创建一个 ComboBoxItem。
-
也就是说,为 MyComboItems 属性添加一个设置器,并在那里调用 OnPropertyChanged。在 Button Click 处理程序中,为属性分配一个新的项目集合。
-
@Clemens 这就是我所做的,但它不起作用。 pastebin.com/raw/67FsEmnR