Skip to main content
 首页 » 编程设计

c#之无法使用控件依赖属性

2024年02月23日16think

我的自定义控件名为“FileSelectDialog”,具有依赖属性:

    public static readonly DependencyProperty FilePathProperty = 
         DependencyProperty.Register("FilePath", typeof(string), typeof(FileSelectDialog)); 
 
    public string FilePath 
    { 
        get { return (string)GetValue(FilePathProperty); } 
        set { SetValue(FilePathProperty, value); } 
    } 

然后我尝试像这样绑定(bind)到这个依赖属性:

    <controls:FileSelectDialog FilePath="{Binding FolderName}"/> 

但没有任何事情发生,我的控件中没有显示初始文本,也没有更新文本保存到“FolderName”属性!我在输出窗口中遇到这样的错误:

    System.Windows.Data Error: 40 : BindingExpression path error: 'FolderName' property not found on 'object' ''FileSelectDialog' (Name='FolderSelector')'. BindingExpression:Path=FolderName; DataItem='FileSelectDialog' (Name='FolderSelector'); target element is 'FileSelectDialog' (Name='FolderSelector'); target property is 'FilePath' (type 'String') 

因此,据我所知,控件尝试在自身上查找属性“FolderName”,而它必须在父控件 DataContext 中查找它。例如,当我使用简单的文本框时:

    <TextBox Text="{Binding Path=FolderName}"/> 

一切正常。

请您参考如下方法:

对我来说似乎是一个基本的 DataContext 问题 您是如何设置 FileSelectDialog Control 的 DataContext 的?似乎您在代码中将 dataContext 设置为“Me”/“this”或在 xaml 中使用“RelativeSource Self”或类似的东西。