DataGridComboBoxColumn绑定到ObservableCollection

时间:2013-04-30 17:24:26

标签: wpf data-binding datagrid datagridcomboboxcolumn

我将“设备与平台”类作为其中一个属性:

public partial class DevicesCollection : ObservableCollection<Device>
{
    public DevicesCollection() : base()
    { }
}

public partial class Device : INotifyPropertyChanged
{
    private string hostIP;
    private string password;
    private int platform;
    private string status = "";
    private int loop = 1;

    public Device() { }

    public Device(string ip, string pswd, int tp)
    {
        HostIP    = ip;
        Password  = pswd;
        Platform  = tp;
        Status    = "Disconnected";
        Loop = 1;
    }        

我还有Platform类:

public partial class PlatformsCollection : ObservableCollection<Platform>
{
    public PlatformsCollection()
        : base()
    {
        Add(new Platform(1, "iOS"));
        Add(new Platform(2, "Android"));
        Add(new Platform(3, "Windows"));
        Add(new Platform(4, "Blackberry"));
    }
}

public partial class Platform : INotifyPropertyChanged
{
    private string platformName;
    private int platformId;

    public Platform(int id, string name)
    {
        PlatformName = name;
        PlatformId = id;
    }
....

我有一个DataGrid绑定到Devices类,其中一列是ComboBox平台,我试图绑定到Platform类:

<DataGridComboBoxColumn x:Name="platform" Header="Platform" CanUserResize="False"
                        ItemsSource="{Binding Platform}"
                        SelectedValueBinding="{Binding Path=Platform.PlatformId}"
                        SelectedValuePath="PlatformId"
                        DisplayMemberPath="PlatformName" Width="100">
    <DataGridComboBoxColumn.ElementStyle>
        <Style TargetType="ComboBox">
            <Setter Property="ItemsSource" Value="{Binding Path=Platform.PlatformName}" />
        </Style>
    </DataGridComboBoxColumn.ElementStyle>
</DataGridComboBoxColumn>

我看到带有值的Dropbox,但在我尝试接收DataGrid.ItemsSource列时选择任何值后,Platform是空的。我做错了什么?我尝试用内置的combobox将列更改为模板 - 结果相同。我会感激任何帮助或至少指导我们。

2 个答案:

答案 0 :(得分:0)

您是否尝试将DataGridComboBoxColumn的{​​{1}}属性绑定到ItemsSource(PlatformsCollection)或属性(平台)?

你应该可以通过类似的东西来实现这个目标。

ObservableCollection

您需要在模型中添加另一个名为SelectedPlatform的成员,每当用户更改所选平台时,该成员将存储/更新。

此外,您可能需要考虑使用<DataGridComboBoxColumn Header="Platform" ItemsSource="{Binding PlatformsCollection}" SelectedValue="{Binding SelectedPlatform}" DisplayMemberPath="PlatformName"/> / CellTemplateCellEditingTemplate的组合,这看起来更好一些。用户只会看到一个文本框,除非他们点击进入组合框的单元格。

此标记类似于

DataGridTemplateColumn

希望这会有所帮助。如果您有任何问题,请告诉我。

答案 1 :(得分:0)

如果您的平台对所有对象都是通用的,那么您可以将平台属性设置为静态,并且您的xaml将使用它,如下所示:

<DataGridComboBoxColumn
    Header="Role"
    SelectedValueBinding="{Binding Role}"
    ItemsSource="{Binding Source={x:Static local:ProjectsDataContext.Roles}}"
    DisplayMemberPath="Name"/>

希望它会有所帮助。