为依赖项属性创建代理

Gam*_*ing 6 c# wpf proxy xaml dependency-properties

我正在尝试创建一个简单的依赖属性代理.我做了一个自定义控件,它是一个文件选择器,它是一个文本框(名称:) "TextBox_FilePath"和一个显示打开文件对话框的按钮.

当我正在进行可重复使用的控制时,我希望它拥有一个"SelectedFilePath"属性.由于该Text属性似乎是我的控件成为"SelectedFilePath"属性的完美,我只想代理这些依赖属性.

我做的第一个方法是:

public static readonly DependencyProperty SelectedFilePathProperty = TextBox.TextProperty;

public string SelectedFilePath
{
    get { return (string) this.TextBox_FilePath.GetValue(SelectedFilePathProperty); }
    set { this.TextBox_FilePath.SetValue(SelectedFilePathProperty, value); }
}
Run Code Online (Sandbox Code Playgroud)

哪个有效,但在尝试绑定到该属性时抛出异常.然后我开始:

public static readonly DependencyProperty SelectedFilePathProperty =
    DependencyProperty.Register("SelectedFilePath", typeof (string), typeof (FilePicker), new PropertyMetadata(default(string)));

public string SelectedFilePath
{
    get { return (string) this.TextBox_FilePath.GetValue(SelectedFilePathProperty); }
    set { this.TextBox_FilePath.SetValue(SelectedFilePathProperty, value); }
}
Run Code Online (Sandbox Code Playgroud)

哪个确实有用,但我不明白为什么?!我在哪里指定我想要text文本框的属性?

简单地代理那个依赖属性我错过了什么?

编辑: 解决方案AddOwner也不起作用,它抛出一个Excetion说"绑定只能应用于依赖属性".码:

public static readonly DependencyProperty SelectedFilePathProperty =
    TextBox.TextProperty.AddOwner(typeof(FilePicker));

public string SelectedFilePath
{
    get { return (string)this.TextBox_FilePath.GetValue(SelectedFilePathProperty); }
    set { this.TextBox_FilePath.SetValue(SelectedFilePathProperty, value); }
}
Run Code Online (Sandbox Code Playgroud)

我不明白什么?

EDIT2: 对于其他有问题理解答案的人,我做了一个小图

H.B*_*.B. 2

第一种方法不起作用,因为该属性仅为注册TextBox,在另一个类中添加引用不会执行任何操作。

第二个只是创建一个全新的字符串属性。

如果你确实想重用就可以调用TextBox.TextPropertyAddOwner

例如

public static readonly DependencyProperty SelectedFilePathProperty =
    TextBox.TextProperty.AddOwner(typeof(FilePicker));
Run Code Online (Sandbox Code Playgroud)

(请注意,此属性已注册为"Text",因此您可能应该像您已经做的那样创建一个具有所需名称的新属性。如果您想拥有相同的属性,我还建议默认设置元数据标志绑定双向绑定行为为TextBox.Text。)