c# - 对象的 WPF 绑定(bind)列表到自定义控件

标签 c# wpf mvvm bind

我正在尝试将设备对象列表绑定(bind)到我正在处理的服装控件。我收到这个错误。

A 'Binding' cannot be set on the 'Devices' property of type 'CamaraSelection'. A 'Binding' can only be set on a DependencyProperty of a 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); }
    }

最佳答案

设置绑定(bind)的属性必须是 DependencyProperty .在您的情况下,它是 Devices -属性(property)。 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); }
}

关于c# - 对象的 WPF 绑定(bind)列表到自定义控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18742025/

相关文章:

c# - 正则表达式拆分字符串但保留分隔符,但不作为单独的元素

c# - 如何插入多个GroupDescription?

wpf - 如何使 WPF DataGrid 单元格右对齐而不使新行上的可选区域变小?

wpf - 下拉菜单中箭头导航的可编辑组合框行为

c# - MVVM - 模型教程?

naming-conventions - Model-View-ViewModel (MVVM) 类和实例的名称应该有多详细?

c# - View 模型应该如何与存储库通信?

c# - LiveCharts (LVC) WPF - 从 DataClick 事件获取图表

java - 本地C# API、android Studio程序

c# - Entity Framework Core 导致无法加载 netstandard