XAML绑定到自定义控件

时间:2013-04-07 15:13:00

标签: wpf vb.net xaml binding

我已经构建了一个自定义控件,并想知道如何在XAML中正确绑定到自定义控件中Observable集合中项的属性。自定义控件属性如下所示。

Public Property MyPoints As ObservableDependencyObjectCollection(Of MyPoint)
    Get
        Return CType(GetValue(MyPointsProperty), ObservableDependencyObjectCollection(Of MyPoint))
    End Get
    Set(value As ObservableDependencyObjectCollection(Of MyPoint))
        SetValue(MyPointsProperty, value)
    End Set
End Property

MyPoint包含两个属性X和Y

完整XAML

<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" xmlns:my="clr-namespace:WpfDependencyPropertyVB">

<Grid>
    <my:CustomControl1   HorizontalAlignment="Left" Margin="322,212,0,0" x:Name="CustomControl11" VerticalAlignment="Top" Width="145" Height="67">
        <my:CustomControl1.MyPoints>
            <my:MyPoint X="100" Y="{Binding Value, ElementName=Slider1}" />
        </my:CustomControl1.MyPoints>
    </my:CustomControl1>
    <Slider Height="26" HorizontalAlignment="Left" Margin="23,174,0,0" Name="Slider1" VerticalAlignment="Top" Width="273" />
    <Label Content="{Binding Value, ElementName=Slider1}" Height="41" HorizontalAlignment="Left" Margin="329,145,0,0" Name="Label1" VerticalAlignment="Top" Width="135" />
</Grid>

在这里输入代码

在我的XAML中,设置如下所示:

<my:CustomControl1 x:Name="CustomControl11" >
    <my:CustomControl1.MyPoints>
        <my:MyPoint X="100" Y="{Binding Value, ElementName=Slider1}" />
    </my:CustomControl1.MyPoints>
</my:CustomControl1>

如果我在控制中设置了一个断点,我可以看到X = 100,但是当Slider Value改变时我没有看到Y被更新。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

我的解决方案是将依赖项属性ThePoint添加到CustomControl1,然后将滑块值绑定到ThePoint.Y。我假设MyPoint派生自DependencyObject,而X和Y是依赖属性。

<my:CustomControl1 x:Name="theControl" />

<Slider Grid.Row="1" Value="{Binding ElementName=theControl, 
        Path=ThePoint.Y, Mode=TwoWay}"/>

然后,您可以根据需要添加PropertyChangedCallback处理程序,以便将项目添加到集合中(如果这是必需的)。

或者,您可以绑定到集合中的项目:

<local:MyCustomControl x:Name="theControl" />

<Slider Grid.Row="1" Value="{Binding ElementName=theControl, 
        Path=MyPoints[0].Y, Mode=TwoWay}" />