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

问题描述 投票:-1回答:2

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

非静态字段,方法或属性“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>

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

c# wpf user-controls wpf-controls
2个回答
1
投票

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

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

DirectorySetter.DirectoryPath = "asd";

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

你可以做的是(xaml):

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

代码背后:

var s = (myUserControl as DirectorySetter).DirectoryPath ;

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

© www.soinside.com 2019 - 2024. All rights reserved.