如何在XAML中分配Control类型的属性 - 错误

时间:2013-07-14 20:53:18

标签: c# .net wpf xaml user-controls

我有一个带有Control类型属性的WPF用户控件,将它与另一个控件(通常是文本框)关联,它将按键发送给。 我可以在XAML中分配此属性,并在运行时编译并运行

但IDE显示错误“38方法或操作未实现。”在Tar​​getControl任务上。

<my:NumericButtonsControl 
 x:Name="NumericButtons" 
 TargetControl="{x:Reference Name=DataEntryTextBox}" />

有问题的用户控制代码如下所示:

public partial class NumericButtonsControl : UserControl
{
    private Control _TargetControl;

    public Control TargetControl
    {
        get 
        {
            return _TargetControl;
        }
        set
        {
            _TargetControl = value;
        }
    }
 }

1 个答案:

答案 0 :(得分:3)

编写WPF应用程序时,您可能希望避免使用x:Reference,因为它是XAML 2009的一项功能,仅适用于松散的XAML。

或者,您可以使用绑定及其ElementName属性。但要实现这一点,您需要使TargetControl成为依赖属性。然后它会是这样的:

<强> C#

public Control TargetControl
{
    get { return (Control)this.GetValue(TargetControlProperty); }
    set { this.SetValue(TargetControlProperty, value); } 
}

public static readonly DependencyProperty TargetControlProperty =
    DependencyProperty.Register("TargetControl",
                                typeof(Control),
                                typeof(NumericButtonsControl),
                                new PropertyMetadata(null));

<强> XAML:

<my:NumericButtonsControl 
    x:Name="NumericButtons" 
    TargetControl="{Binding ElementName=DataEntryTextBox}" />