【发布时间】:2014-01-28 03:10:08
【问题描述】:
我试图通过将项目视图样式中的Canvas.Left 和Canvas.Top 属性绑定到视图模型中的适当属性来反映我的视图模型中的一个位置,该位置表示对象在我的视图中的位置.但是,绑定似乎不起作用。
对于这个最小的示例,我已经简化了结构,因此只有一个控件Thing 是样式化和模板化的:
using System;
using System.Windows;
using System.Windows.Controls;
namespace LocationBinding
{
public class Thing : Control
{
static Thing()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(Thing), new FrameworkPropertyMetadata(typeof(Thing)));
}
public Point Location {
get {
return new Point(70, 70);
}
}
public double VPos {
get {
return 100;
}
}
}
}
为了简单起见,我在主窗口的资源字典中声明了样式——一个带有画布的简单窗口(我的真实项目在Themes\Generic.xaml中有这个)。在它的风格中,我绑定到控件的属性值:
<Window x:Class="LocationBinding.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:LocationBinding"
Title="LocationBinding" Height="300" Width="300">
<Window.Resources>
<Style TargetType="local:Thing">
<Setter Property="Panel.ZIndex" Value="542"/>
<Setter Property="Canvas.Left" Value="{Binding Location.X}"/>
<Setter Property="Canvas.Top" Value="{Binding VPos}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:Thing">
<Ellipse Fill="ForestGreen" Width="30" Height="30"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Canvas Name="cnv">
</Canvas>
</Window>
主窗口的代码隐藏只是将Thing 实例添加到画布:
using System;
using System.Windows;
namespace LocationBinding
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
cnv.Children.Add(new Thing());
}
}
}
样式已正确应用,ZIndex 值(根据 Snoop)和控件基于模板的正确外观证明了这一点。然而,Canvas.Left 和 Canvas.Top 保持未设置(因此 Thing 粘在画布的左上角),即使根据诸如 this 或 this 之类的线程,Property="Canvas.Left" 似乎是引用样式中附加属性的正确语法。
我首先尝试将 Canvas.Top 绑定到 Location.Y 并将其替换为 VPos 属性,以防问题与绑定到结构属性有关,但这似乎也没有改变任何东西。
我错过了什么;如何以我的风格将Canvas.Left 和Canvas.Top 绑定到我的Thing.Location 属性的坐标?
【问题讨论】:
标签: wpf binding attached-properties