【发布时间】:2013-11-11 18:50:48
【问题描述】:
我正在努力绑定到依赖属性。
我的应用程序有一个主窗口。这是一个用户控件(称为时间线)。在 TimeLine UserControl 中是另一个名为 MoveMe 的控件。
我可以从主窗口绑定到时间线用户控件的依赖属性。当我使用OneWayToSource 绑定时,我可以从 MoveMe 绑定到 MoveMe UserControl。但是,我正在尝试从时间线 UserControl 绑定到 MoveMe 控件(从父级到子级)。但是,绑定不起作用。我在 MoveMe 属性的设置器上放了一个手表,它从未被触发。
“输出”窗口中没有绑定问题。
我的 MainWindow.xaml 有
<timeline:TimeLine StartTime="{Binding StartTime}"
EndTime="{Binding EndTime}"
TestEvents="{Binding TestEvents}"
CampaignDetails="{Binding CampaignDetails}"
ShowReportPeriod="True" HorizontalAlignment="Stretch"/>
我的timeline.xaml 有
<userControls:MoveMe
StartMarkerPositionPixels="{Binding RelativeSource={RelativeSource AncestorType=userControls:TimeLine}, Path=StartMarkerPosition, Mode=OneWayToSource}"
EndReportPositionInPixels="{Binding RelativeSource={RelativeSource AncestorType=userControls:TimeLine}, Path=EndOfReportPosition, Mode=OneWay}"
x:Name="ReportSelectorStart" />
它的 DataContext 设置如下
<UserControl DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorLevel=1,AncestorType=Window}}"...
因此,正如您在上面看到的,在timeline.xaml 中绑定了2 个属性,第一个是StartMarkerPositionPixels,即OneWayToSource。这工作正常。问题是第二个,EndReportPositionInPixels,因为它不绑定。
MoveMe 控件背后的代码
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
namespace TimeLineCanvas.UserControls
{
/// <summary>
/// Interaction logic for MoveMe.xaml
/// </summary>
public partial class MoveMe : UserControl
{
public MoveMe()
{
InitializeComponent();
//this.DataContext = this;
}
public double StartMarkerPositionPixels
{
get { return (double)GetValue(StartMarkerPositionProperty); }
set { SetValue(StartMarkerPositionProperty, value); }
}
public double EndReportPositionInPixels
{
get { return (double)GetValue(ScaleFactorProperty); }
set { SetValue(ScaleFactorProperty, value);
OnPropertyChanged("EndReportPositionInPixels");
}
}
public static readonly DependencyProperty EndMarkerPositionProperty = DependencyProperty.Register(
"EndMarkerPositionPixels",
typeof(double),
typeof(MoveMe));
public static readonly DependencyProperty EndReportPositionInPixelsPoperty = DependencyProperty.Register(
"EndReportPositionInPixels",
typeof(double),
typeof(MoveMe));
}
}
在我的 TimeLine 代码隐藏中,我有以下内容
private double _endOfReportPosition;
public double EndOfReportPosition
{
get { return _endOfReportPosition; }
set
{
_endOfReportPosition = value;
//this.ReportSelectorStart.EndMarkerPositionPixels = value;//If I hardcode it in, then it works, but I want it bind
OnPropertyChanged("EndOfReportPosition");
}
}
输出窗口确认没有绑定错误。
我的问题是,如何通过依赖属性将值从 TimeLine 控件传递到 MoveMe 控件。
【问题讨论】:
-
忠告。看看输出。如果有任何绑定错误,则会在此处列出
-
谢谢@David,很遗憾,没有错误
-
您是否在加载事件后检查了
EndReportPositionInPixels的值并附加了调试器? Setter 断点肯定不会被命中,但请检查它的值是否正确。 -
是的,在我的 MoveMe 背后的代码中,我有一个触发事件。我在其中设置了断点,
EndReportPositionInPixels的值仅在硬编码时才会填充。如果我绑定,它不起作用。
标签: c# wpf xaml user-controls