【发布时间】:2010-08-19 22:07:05
【问题描述】:
这是我的用户控件的顶部:
<UserControl x:Class="MyApp.Common.Controls.Views.SimpleView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:Framework="http://www.memoryexpress.com/UIFramework"
mc:Ignorable="d"
Height="130" Width="450"
x:Name="Master"
>
<!-- Behaviour under the context of the generic dialog -->
<Framework:DialogMetadata.Instance>
<Framework:DialogMetadata SizeToContent="WidthAndHeight"
ResizeMode="NoResize"
ConfirmCommand="{Binding ConfirmCommand, RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type UserControl}}}"
ConfirmButtonText="Run"/>
</Framework:DialogMetadata.Instance>
长话短说,我有一个 UserControl,并且我定义了一个附加属性:DialogMetadata.Instance,它接受一个类型为 DialogMetadata 的对象。如果我将此控件作为独立对话框启动时,此构造只是一个附加属性列表供我使用。
这在大多数情况下都有效,我已经找到了 SizeToContent、ResizeMode 和 ConfirmButtonText。
但是,本着 MVVM 的精神,我想将此命令传递给对话框,以便在我们单击确认按钮时执行。如您所见,我尝试将 ViewModel 中的命令绑定到 DialogMetadata 的 ConfirmCommand DependencyProperty。
DP 是这样定义的:
#region DP - ConfirmCommand
public static DependencyProperty ConfirmCommandProperty =
DependencyProperty.Register("ConfirmCommand", typeof (IBaseCommand), typeof (DialogMetadata),
new PropertyMetadata(null));
/// <summary>
/// The Confirmation Command for a dialog. This allows us to sync up to the user-control for
/// determining if we can can hit the Ok Button, and to perform additional logic
/// </summary>
public virtual IBaseCommand ConfirmCommand
{
get { return GetValue(ConfirmCommandProperty) as IBaseCommand; }
set { SetValue(ConfirmCommandProperty, value); }
}
#endregion
但是,当我像在第一个代码块中那样绑定时:(注意:属性“ConfirmCommand”存在于 UserControl 的数据上下文中,并且具有非空值。)
绑定
{Binding ConfirmCommand, RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type UserControl}}}
错误
System.Windows.Data 错误:4:无法通过引用“RelativeSource FindAncestor,AncestorType='System.Windows.Controls.UserControl',AncestorLevel='1'”找到绑定源。绑定表达式:路径=确认命令;数据项=空;目标元素是 'DialogMetadata' (Name='');目标属性是“ConfirmCommand”(输入“IBaseCommand”)
绑定
{Binding ConfirmCommand, ElementName=Master}
错误
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=Master'. BindingExpression:Path=ConfirmCommand; DataItem=null; target element is 'DialogMetadata' (Name=''); target property is 'ConfirmCommand' (type 'IBaseCommand')
有人知道我的绑定发生了什么吗?
【问题讨论】:
标签: .net wpf data-binding