无法访问用户控件上的公共属性wpf c#

时间:2017-12-21 00:22:25

标签: c# wpf user-controls wpf-controls

我正在尝试访问用户控件上的公共属性,但我收到此消息。我认为我不需要初始化用户控件吗?当我尝试访问公共属性DirectorySetter.DirectoryPath时,我会收到以下消息:

  

非静态字段,方法或者需要对象引用   property'DirectorySetter.DirectoryPath'

这是我的用户控件代码隐藏:

public partial class DirectorySetter : UserControl
    {
        public DirectorySetter()
        {
            InitializeComponent();
        }

        public string DirectoryPath
        {
            get
            {
                return txtDirectoryPath.Text;
            }
            set
            {
                txtDirectoryPath.Text = value;
            }
        }
    }

以下是使用用户控件的xaml:

<Page
      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:local="clr-namespace:PhotoOrganizer.Pages"
      xmlns:UserControls="clr-namespace:PhotoOrganizer.UserControls" x:Class="PhotoOrganizer.Pages.PhotoDirectoryPath"
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300"
      Title="PhotoDirectoryPath">

    <Grid>
        <TextBlock HorizontalAlignment="Left" Margin="69,91,0,0" TextWrapping="Wrap" Text="Set your photo directory path" VerticalAlignment="Top"/>

        <UserControls:DirectorySetter HorizontalAlignment="Left" Margin="22,135,0,0" VerticalAlignment="Top"/>
        <Button Name="btnSave" Content="Save" HorizontalAlignment="Left" Margin="155,178,0,0" VerticalAlignment="Top" Width="75" Click="btnSave_Click"/>

    </Grid>
</Page>

任何建议或帮助都会很棒!

2 个答案:

答案 0 :(得分:1)

您没有发布实际发生错误的代码,您尝试访问该“公共属性”

所以我可能只是猜测你正在尝试做类似

的事情
DirectorySetter.DirectoryPath = "asd";

由于您的课程和您的财产不是静态的,因此无效。

你可以做的是(xaml):

 <UserControls:DirectorySetter x:Name="myUserControl"/>

代码背后:

var s = (myUserControl as DirectorySetter).DirectoryPath ;

答案 1 :(得分:0)

如果您想从xaml访问您的属性并绑定它,则需要在UserControl类中实现依赖属性

// Dependency Property
public static readonly DependencyProperty DirectoryPathProperty = 
     DependencyProperty.Register( "DirectoryPath", typeof(string),
     typeof(DirectorySetter), new FrameworkPropertyMetadata(string.Empty));

// .NET Property wrapper
public string DirectoryPath
{
    get { return (string)GetValue(DependencyProperty ); }
    set { SetValue(DependencyProperty , value); }
}

来自Msdn的其他资源

Dependency properties overview