I am by no means an expert on WPF so this is probably very simple. I'm trying to bind a List to a combobox. It works in code, it doesn't work in xaml. If I remove the ItemsSource from the constructor, it doesn't work, which is how I know. I thought I had the equivalent in xaml, but apparently it's not.
xaml:
<ComboBox Height="23"
HorizontalAlignment="Left"
Margin="146,76,0,0"
Name="comboBox1"
VerticalAlignment="Top"
Width="120"
ItemsSource="{Binding AvailableActions}"
DisplayMemberPath="Name"
SelectedValue开发者_StackOverflowPath="Name"
SelectedValue="Replace" />
constructor:
public MainWindow()
{
_availableActions = new List<IMapperAction>
{
new ReplaceAction(),
new CollapseAction(),
new NewBasedOnAction()
};
InitializeComponent();
Loaded += OnWindowLoaded;
comboBox1.ItemsSource = AvailableActions;
}
Well, you need to set the DataContext
of the main window:
public MainWindow()
{
_availableActions = new List<IMapperAction>
{
new ReplaceAction(),
new CollapseAction(),
new NewBasedOnAction()
};
InitializeComponent();
DataContext = this;
Loaded += OnWindowLoaded;
}
As suggested here, you have to set the DataContext.
You can also read this link to know why and when which of the two should be used:
Why are DataContext and ItemsSource not redundant?
精彩评论