Search code examples
c#wpfuser-controlswpf-controls

Can't access public property on user control wpf c#


I'm trying to access a public property on a user control but I am getting this message. I don't think I would need to initialize the user control right? When I try to access the public property DirectorySetter.DirectoryPath I would get this message:

An object reference is required for the non-static field, method, or property 'DirectorySetter.DirectoryPath'

Here is my user control code-behind:

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

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

Here is the xaml that uses the user control:

<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>

Any suggestion or help would be great!


Solution

  • You didn't post the code where there error actually happens, where you try to access that "public property"

    So I might just guess that you're trying to do something like

    DirectorySetter.DirectoryPath = "asd";
    

    which won't work since your class and your property aren't static.

    What you can do though, is (xaml):

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

    Code behind:

    var s = (myUserControl as DirectorySetter).DirectoryPath ;