WPF将对象绑定到自定义控件的列表

时间:2013-09-11 13:04:44

标签: c# wpf mvvm bind

我正在尝试将设备对象List绑定到我正在处理的服装控件上。我收到了这个错误。

  

无法在类型的“设备”属性上设置“绑定”   'CamaraSelection'。 '绑定'只能在DependencyProperty上设置   DependencyObject。

xml代码

<trainControl:CamaraSelection  Devices="{Binding DeviceList}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>

控制代码

    private List<Device> devices = new List<Device>();
    public static readonly DependencyProperty DeviceListProperty =
    DependencyProperty.Register("DeviceList", typeof(List<Device>), typeof(CamaraSelection),
                            new PropertyMetadata(default(ItemCollection), OnDeviceListChanged));


    private static void OnDeviceListChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
    {
        var camaraSelection = dependencyObject as CamaraSelection;

        if (camaraSelection != null)
        {
            camaraSelection.OnDeviceListChanged(dependencyPropertyChangedEventArgs);
        }
    }
    private void OnDeviceListChanged(DependencyPropertyChangedEventArgs e)
    {

    }

    public List<Device> Devices
    {
        get { return (List<Device>)GetValue(DeviceListProperty); }
        set { SetValue(DeviceListProperty, value); }
    }

2 个答案:

答案 0 :(得分:3)

设置绑定的属性必须是DependencyProperty。在你的情况下,它是Devices - 属性。 DependencyProperty.Register()方法中的第一个参数必须是您的属性的名称。代码中的第一个参数是"DeviceList",但您的Property的名称是Devices

public static readonly DependencyProperty DevicesProperty =
DependencyProperty.Register("Devices", typeof(List<Device>), typeof(CamaraSelection),
                        new PropertyMetadata(default(ItemCollection), OnDeviceListChanged));


public List<Device> Devices
{
    get { return (List<Device>)GetValue(DevicesProperty ); }
    set { SetValue(DevicesProperty, value); }
}

答案 1 :(得分:2)

“设备”类中的属性必须是依赖项属性,而不是“DeviceList”。您绑定的属性必须是依赖项属性。