简体   繁体   中英

XAML Binding to custom control

I have built a custom control and want to know how to properly bind in XAML to a property of an item in an Observable collection in the custom control. The custom control property looks like this.

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 contains two properties X and Y

Full 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>

enter code here

In My XAML the set up looks like this:

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

If I set a break point in my control I can see that X=100 but i don't see that Y is updated when the Slider Value changes.

Any help would be greatly appreciated.

My solution would be to add a dependency property ThePoint to CustomControl1 and then bind the slider value to ThePoint.Y . I'm assuming that MyPoint derives from DependencyObject and that X and Y are dependency properties.

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

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

You could then add PropertyChangedCallback handlers as required to add items to the collection (if that's what's required).

Alternatively you can bind to an item in the collection:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM