如何将自定义XAML成员添加到自定义面板(例如网格面板的Grid.RowDefinitions成员)



我有一个自定义面板:

public class DevicesPanel : Canvas { ... }

被这样使用:

<vc:DevicesPanel>
    ...
</vc:DevicesPanel>

如何添加XAML属性,例如Grid面板的Grid.RowDefinitions?可以这样使用:

<vc:DevicesPanel>
    <vc:DevicesPanel.Data/>
    ...
</vc:DevicesPanel>

也喜欢这样:

<vc:DevicesPanel>
    <vc:DevicesPanel.Data>
        ...
    </vc:DevicesPanel.Data>
    ...
</vc:DevicesPanel>

编辑:

我尝试了:

public class DevicesPanel : Canvas {
        public static readonly DependencyProperty XyProperty =
            DependencyProperty.Register("Xy", 
                typeof (IEnumerable<UIElement>),
                typeof (DevicesPanel),
                new PropertyMetadata(default(IEnumerable<UIElement>)));
    public IEnumerable<UIElement> Xy {
        get { return (Collection<UIElement>)GetValue(XyProperty); }
        set { SetValue(XyProperty, value); }
    }
    ...
}

但这不会编译(错误在XAML零件上):

<vc:DevicesPanel>
    <vc:DevicesPanel.Xy></vc:DevicesPanel.Xy>
    ...
<vc:DevicesPanel>

错误是:

Property 'Xy' does not have a value.
The attachable property 'Xy' was not found in type 'DevicesPanel'.
The member "Xy" is not recognized or is not accessible.

(也尝试过Collection而不是IEnumerable

作为 Grid.RowDefinitions只是一个公共属性,您可以将此属性添加到DevicesPanel类中。

// DevicesPanel.cs
public class DevicesPanel : Canvas
{
    public List<string> Data { get; set; }
}

// MainWindow.xaml
<wpfApplication1:DevicesPanel>
    <wpfApplication1:DevicesPanel.Data>
        <system:String>Item1</system:String>
        <system:String>Item2</system:String>
        <system:String>Item3</system:String>
    </wpfApplication1:DevicesPanel.Data>
</wpfApplication1:DevicesPanel>

最新更新