使用mvvm和caliburn.micro在数据网格中组合框

时间:2018-04-04 09:52:43

标签: wpf mvvm combobox datagrid caliburn.micro

我已经尝试了几天使用MVVM和Caliburn.Micro在数据网格中添加一个组合框。
我已经尝试了几乎所有我能找到的建议 - 没有运气!

我的Xaml在用户控件中 - 名称和测试显示正常!

XAML:

<DataGrid x:Name="Players" AutoGenerateColumns="False" Height="200" HorizontalAlignment="Left"  VerticalAlignment="Top" Width="308">    
    <DataGrid.Columns>
        <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
        <DataGridTextColumn Header="Test" Binding="{Binding Position}"/>
        <DataGridComboBoxColumn x:Name="ComboBoxColumn" Header="Position"  SelectedItemBinding="{Binding Position}"/>
    </DataGrid.Columns>
</DataGrid>

视图模型:

public class MissingCTypeViewModel : Screen, INotifyPropertyChanged
{
    public ObservableCollection<Player> Players { get; set; }
    public ObservableCollection<string> Positions { get; set; }

    public MissingCTypeViewModel()
    {

        Positions = new ObservableCollection<string>() { "Forward", "Defense", "Goalie" };
        Players = new ObservableCollection<Player>(){
                new Player() {Name = "Tom",Position= "Forward"},
                new Player() {Name = "Dick", Position= "Defense"},
                new Player() {Name = "Harry", Position= "Goalie"}
            };
        //ComboBoxColumn.ItemsSource = Positions;
        //dataGrid1.ItemsSource = Players;
    }
}

public class Player
{
    public string Name { set; get; }
    public string Position { set; get; }
}

结果:

https://i.stack.imgur.com/aGuUF.png

1 个答案:

答案 0 :(得分:0)

您遗漏了DataGridComboBoxColumn ItemsSourcePositions集合的绑定。

请注意,您需要将其作为静态资源 - 请参阅:Binding ItemsSource of a ComboBoxColumn in WPF DataGrid

XAML:

xmlns:vm="clr-namespace:TheNamespeceOfYourApp.ViewModels"

<DataGrid.Columns>
    <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
    <DataGridTextColumn Header="Test" Binding="{Binding Position}"/>
    <DataGridComboBoxColumn x:Name="ComboBoxColumn" Header="Position"  SelectedItemBinding="{Binding Position}" ItemsSource="{Binding Source={x:Static vm:MissingCTypeViewModel.Positions}}"/>
</DataGrid.Columns>

视图模型:

public static List<string> Positions = new List<string>() { "Forward", "Defense", "Goalie" };`