我试图将Canvas.Left
和Canvas.Top
附加属性绑定到我的自定义X和Y属性,没有成功,我使用以下XAML。
<Style TargetType="{x:Type layout:BankBaseControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type layout:BankBaseControl}">
<ContentPresenter Content="{TemplateBinding Marker}" >
<ContentPresenter.ContentTemplate>
<DataTemplate>
<Ellipse Fill="Red" Width="{Binding Width}"
Height="{Binding Height}"
Canvas.Left="{Binding X, Mode=TwoWay}"
Canvas.Top="{Binding Y, Mode=TwoWay}"/>
</DataTemplate>
</ContentPresenter.ContentTemplate>
</ContentPresenter>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
样式被正确应用(宽度和高度绑定工作正常),但是附加的属性似乎没有看到X和Y值。我尝试从代码中执行此绑定:
SetBinding(Canvas.LeftProperty, new Binding("X")
{ Source = Marker, Mode = BindingMode.TwoWay });
它工作了,但我更想从XAML来做。
编辑:我还尝试将XAML中的绑定更改为Canvas.Left="100" Canvas.Top="100"
,但没有运气,椭圆仍然会显示在坐标0,0上。
您所拥有的无效。你的Ellipse不是Canvas的子元素,所以Canvas附加的属性不会被使用。你的Ellipse是ContentPresenter的子元素,而ContentPresenter是BankBaseControl的子元素。
您需要在BankBaseControl上设置附加属性,假设它托管在Canvas面板中,如下所示:
<Style TargetType="{x:Type layout:BankBaseControl}">
<Setter Property="Canvas.Left" Value="{Binding RelativeSource="{RelativeSource Self}, Path=Marker.X, Mode=TwoWay}" />
<Setter Property="Canvas.Top" Value="{Binding RelativeSource="{RelativeSource Self}, Path=Marker.Y, Mode=TwoWay}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type layout:BankBaseControl}">
<ContentPresenter Content="{TemplateBinding Marker}" >
<ContentPresenter.ContentTemplate>
<DataTemplate>
<Ellipse Fill="Red" Width="{Binding Width}" Height="{Binding Height}" />
</DataTemplate>
</ContentPresenter.ContentTemplate>
</ContentPresenter>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>